<?php if(!defined('DEBUG'))exit;defined('ROOT') OR define('ROOT','D:\wamp\www\ZBZphp\wowsai\Connect2.1\API/');defined('CLASS_PATH') OR define('CLASS_PATH','D:\wamp\www\ZBZphp\wowsai\Connect2.1\API/class/');defined('DEBUG') OR define('DEBUG','');defined('DEBUG_TOOL') OR define('DEBUG_TOOL','');defined('MODULE_LIST') OR define('MODULE_LIST','Index,Admin');defined('APP_PATH') OR define('APP_PATH','Application/');defined('HDPHP_VERSION') OR define('HDPHP_VERSION','2014-12-21');defined('TEMP_PATH') OR define('TEMP_PATH','Application/Temp/');defined('TEMP_FILE') OR define('TEMP_FILE','Application/Temp/~Boot.php');defined('HDPHP_PATH') OR define('HDPHP_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/');defined('MAGIC_QUOTES_GPC') OR define('MAGIC_QUOTES_GPC','');defined('ROOT_PATH') OR define('ROOT_PATH','ZBZphp/wowsai/');defined('DS') OR define('DS','\\');defined('IS_CGI') OR define('IS_CGI','');defined('IS_WIN') OR define('IS_WIN','\\');defined('IS_CLI') OR define('IS_CLI','');defined('HDPHP_DATA_PATH') OR define('HDPHP_DATA_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Data/');defined('HDPHP_LIB_PATH') OR define('HDPHP_LIB_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Lib/');defined('HDPHP_CONFIG_PATH') OR define('HDPHP_CONFIG_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Config/');defined('HDPHP_CORE_PATH') OR define('HDPHP_CORE_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Lib/Core/');defined('HDPHP_EXTEND_PATH') OR define('HDPHP_EXTEND_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Extend/');defined('HDPHP_ORG_PATH') OR define('HDPHP_ORG_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Extend/Org/');defined('HDPHP_TPL_PATH') OR define('HDPHP_TPL_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Lib/Tpl/');defined('HDPHP_DRIVER_PATH') OR define('HDPHP_DRIVER_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Lib/Driver/');defined('HDPHP_FUNCTION_PATH') OR define('HDPHP_FUNCTION_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Lib/Function/');defined('HDPHP_LANGUAGE_PATH') OR define('HDPHP_LANGUAGE_PATH','D:/wamp/www/ZBZphp/wowsai/hdphp/Lib/Language/');defined('STATIC_PATH') OR define('STATIC_PATH','Static/');defined('APP_COMMON_PATH') OR define('APP_COMMON_PATH','Application/Common/');defined('APP_CONFIG_PATH') OR define('APP_CONFIG_PATH','Application/Common/Config/');defined('APP_MODEL_PATH') OR define('APP_MODEL_PATH','Application/Common/Model/');defined('APP_CONTROLLER_PATH') OR define('APP_CONTROLLER_PATH','Application/Common/Controller/');defined('APP_LANGUAGE_PATH') OR define('APP_LANGUAGE_PATH','Application/Common/Language/');defined('APP_ADDON_PATH') OR define('APP_ADDON_PATH','Application/Addons/');defined('APP_HOOK_PATH') OR define('APP_HOOK_PATH','Application/Common/Hook/');defined('APP_TAG_PATH') OR define('APP_TAG_PATH','Application/Common/Tag/');defined('APP_LIB_PATH') OR define('APP_LIB_PATH','Application/Common/Lib/');defined('APP_COMPILE_PATH') OR define('APP_COMPILE_PATH','Application/Temp/Compile/');defined('APP_CACHE_PATH') OR define('APP_CACHE_PATH','Application/Temp/Cache/');defined('APP_TABLE_PATH') OR define('APP_TABLE_PATH','Application/Temp/Table/');defined('APP_LOG_PATH') OR define('APP_LOG_PATH','Application/Temp/Log/');final class App { public static function run() { session(C("SESSION_OPTIONS")); Hook::listen("APP_INIT"); Hook::listen("APP_BEGIN"); DEBUG and Debug::start("APP_BEGIN"); self::start(); DEBUG and Debug::show("APP_BEGIN", "APP_END"); !DEBUG and C('LOG_RECORD') and Log::save(); Hook::listen("APP_END"); } static private function start() { $controller = controller(CONTROLLER); if (!$controller) { if(!is_dir(MODULE_PATH)){ _404('模块' .MODULE . '不存在'); } $controller = Controller("Empty"); if (!$controller) { _404('控制器' . CONTROLLER .C("CONTROLLER_FIX") .'不存在'); } } try { $action = new ReflectionMethod($controller, ACTION); if ($action->isPublic()) { $action->invoke($controller); } else { throw new ReflectionException; } } catch (ReflectionException $e) { $action = new ReflectionMethod($controller, '__call'); $action->invokeArgs($controller, array(ACTION, '')); } } }abstract class Controller { protected $view = null; protected $options = array(); public function __construct() { Hook::listen('CONTROLLER_START', $this->options); $this->view = ViewFactory::factory(); if (method_exists($this, "__init")) { $this->__init(); } } public function __call($action, $args) { if (strcasecmp($action, ACTION) == 0) { if (method_exists($this, "__empty")) { $this->__empty($args); } else { _404('控制器中不存在动作' . $action); } } } public function __set($name, $value) { $this->assign($name, $value); } protected function display($tplFile = null, $cacheTime = -1, $cachePath = null, $contentType = "text/html", $show = true) { Hook::listen("VIEW_START"); $status = $this->view->display($tplFile, $cacheTime, $cachePath, $contentType, $show); Hook::listen("VIEW_END"); return $status; } protected function fetch($tplFile = null, $cacheTime = null, $cachePath = null, $contentType = "text/html") { return $this->view->fetch($tplFile, $cacheTime, $cachePath, $contentType); } protected function isCache($cachePath = null) { $args = func_get_args(); return call_user_func_array(array($this->view, "isCache"), $args); } protected function assign($name, $value = null) { return $this->view->assign($name, $value); } protected function error($message = '出错了', $url = NULL, $time = 2, $tpl = null) { if (IS_AJAX) { $this->ajax(array('status' => 0, 'message' => $message)); } else { $url = $url ? "window.location.href='" . U($url) . "'" : "window.location.href='" . __HISTORY__ . "'"; $tpl = $tpl ? $tpl : (strstr(C("TPL_ERROR"), '/') ? C("TPL_ERROR") : MODULE_PUBLIC_PATH . C("TPL_ERROR")); $this->assign(array("message" => $message, 'url' => $url, 'time' => $time)); $this->display($tpl); } exit; } protected function success($message = '操作成功', $url = NULL, $time = 2, $tpl = null) { if (IS_AJAX) { $this->ajax(array('status' => 1, 'message' => $message)); } else { $url = $url ? "window.location.href='" . U($url) . "'" : "window.location.href='" . __HISTORY__ . "'"; $tpl = $tpl ? $tpl : (strstr(C("TPL_SUCCESS"), '/') ? C("TPL_SUCCESS") : MODULE_PUBLIC_PATH . C("TPL_SUCCESS")); $this->assign(array("message" => $message, 'url' => $url, 'time' => $time)); $this->display($tpl); } exit; } protected function ajax($data, $type = "JSON") { $type = strtoupper($type); switch ($type) { case "HTML" : case "TEXT" : $_data = $data; break; case "XML" : $_data = Xml::create($data, "root", "UTF-8"); break; default : $_data = json_encode($data); } echo $_data; exit; } public function createHtml($htmlFile, $htmlPath, $template) { $content = $this->fetch($template); $file = $htmlPath . $htmlFile; $Storage = Storage::init(); return $Storage->save($file, $content); } public function __destruct() { Hook::listen('CONTROLLER_END', $this->options); } }final class Debug { static $info = array(); static $runtime; static $memory; static $memory_peak; static $sqlExeArr = array(); static $tpl = array(); static $cache=array("write_s"=>0,"write_f"=>0,"read_s"=>0,"read_f"=>0); static public function start($start) { self::$runtime[$start] = microtime(true); if (function_exists("memory_get_usage")) { self::$memory[$start] = memory_get_usage(); } if (function_exists("memory_get_peak_usage")) { self::$memory_peak[$start] = false; } } static public function runtime($start, $end = '', $decimals = 4) { if (!isset(self::$runtime[$start])) { throw new HdException('没有设置调试开始点：' . $start); } if (empty(self::$runtime[$end])) { self::$runtime[$end] = microtime(true); return number_format(self::$runtime[$end] - self::$runtime[$start], $decimals); } } static public function memory_perk($start, $end = '') { if (!isset(self::$memory_peak[$start])) return mt_rand(200000, 1000000); if (!empty($end)) self::$memory_peak[$end] = memory_get_peak_usage(); return max(self::$memory_peak[$start], self::$memory_peak[$end]); } static public function show($start, $end) { $debug = array(); $debug['file'] = require_cache(); $debug['runtime'] = self::runtime($start, $end); $debug['memory'] = number_format(self::memory_perk($start, $end) / 1000, 0) . " KB"; require HDPHP_PATH . 'Lib/Tpl/debug.html'; } }abstract class Hook { static private $hook = array(); static public function add($hook, $action) { if (!isset(self::$hook[$hook])) { self::$hook[$hook] = array(); } if (is_array($action)) { self::$hook[$hook] = array_merge(self::$hook[$hook], $action); } else { self::$hook[$hook][] = $action; } } static public function get($hook = '') { if (empty($hook)) { return self::$hook; } else { return self::$hook[$hook]; } } static public function import($data, $recursive = true) { if ($recursive === false) { self::$hook = array_merge(self::$hook, $data); } else { foreach ($data as $hook => $value) { if (!isset(self::$hook[$hook])) self::$hook[$hook] = array(); if (isset($value['_overflow'])) { unset($value['_overflow']); self::$hook[$hook] = $value; } else { self::$hook[$hook] = array_merge(self::$hook[$hook], $value); } } } } static public function listen($hook, &$param = null) { if (!isset(self::$hook[$hook])) return false; foreach (self::$hook[$hook] as $name) { if (false == self::exe($name, $hook, $param)) return; } } static public function exe($name, $action, &$param = null) { if (substr($name, -4) == 'Hook') { $action = 'run'; } else { require_cache(APP_ADDON_PATH . $name . '/' . $name . 'Addon.class.php'); $name = $name . 'Addon'; if (!class_exists($name, false)) return false; } $obj = new $name; if(method_exists($obj,$action)) $obj->$action($param); return true; } }final class HDPHP { static public function init() { is_file(APP_CONFIG_PATH . 'config.php') and C(require(APP_CONFIG_PATH . 'config.php')); is_file(APP_LANGUAGE_PATH . C('LANGUAGE') . '.php') and L(require APP_LANGUAGE_PATH . C('LANGUAGE') . '.php'); Route::parseUrl(); Hook::import(C('HOOK')); in_array(MODULE,C('DENY_MODULE')) && halt(MODULE.'模块禁止使用'); if(!defined('MODULE_PATH')){ if(empty($_GET[C('VAR_GROUP')])){ define('MODULE_PATH',APP_PATH.MODULE.'/'); }else if($_GET[C('VAR_GROUP')]=='Addon'){ define('MODULE_PATH',APP_ADDON_PATH.MODULE.'/'); }else{ define('MODULE_PATH',APP_PATH.$_GET[C('VAR_GROUP')].'/'.MODULE.'/'); } } defined('MODULE_CONTROLLER_PATH') or define('MODULE_CONTROLLER_PATH', MODULE_PATH . 'Controller/'); defined('MODULE_MODEL_PATH') or define('MODULE_MODEL_PATH', MODULE_PATH . 'Model/'); defined('MODULE_CONFIG_PATH') or define('MODULE_CONFIG_PATH', MODULE_PATH . 'Config/'); defined('MODULE_HOOK_PATH') or define('MODULE_HOOK_PATH', MODULE_PATH . 'Hook/'); defined('MODULE_LANGUAGE_PATH') or define('MODULE_LANGUAGE_PATH', MODULE_PATH . 'Language/'); defined('MODULE_TAG_PATH') or define('MODULE_TAG_PATH', MODULE_PATH . 'Tag/'); defined('MODULE_LIB_PATH') or define('MODULE_LIB_PATH', MODULE_PATH . 'Lib/'); is_file(MODULE_CONFIG_PATH . 'config.php') and C(require(MODULE_CONFIG_PATH . 'config.php')); is_file(MODULE_LANGUAGE_PATH . C('LANGUAGE') . '.php') and L(require MODULE_LANGUAGE_PATH . C('LANGUAGE') . '.php'); defined('MODULE_VIEW_PATH') or define('MODULE_VIEW_PATH',strstr(C('TPL_PATH'),'/')?C('TPL_PATH').C('TPL_STYLE'): MODULE_PATH.C('TPL_PATH').'/'.C('TPL_STYLE')); defined('MODULE_PUBLIC_PATH') or define('MODULE_PUBLIC_PATH', MODULE_VIEW_PATH .'Public/'); defined('CONTROLLER_VIEW_PATH') or define('CONTROLLER_VIEW_PATH',MODULE_VIEW_PATH.CONTROLLER.'/'); defined("__STATIC__") or define('__STATIC__', __ROOT__ . '/Static'); defined('__HDPHP_TPL__') or define('__HDPHP_TPL__',__HDPHP__.'/Lib/Tpl'); defined("__VIEW__") or define('__VIEW__', __ROOT__ . '/'.rtrim(MODULE_VIEW_PATH,'/')); defined("__PUBLIC__") or define('__PUBLIC__', __VIEW__ . '/Public'); defined("__CONTROLLER_VIEW__") or define('__CONTROLLER_VIEW__', __VIEW__ .'/'. CONTROLLER); define("__HISTORY__", isset($_SERVER["HTTP_REFERER"])?$_SERVER["HTTP_REFERER"]:null); date_default_timezone_set(C('DEFAULT_TIME_ZONE')); @ini_set('memory_limit', '128M'); @ini_set('register_globals', 'off'); @ini_set('magic_quotes_runtime', 0); define('NOW', $_SERVER['REQUEST_TIME']); define('NOW_MICROTIME', microtime(true)); define('REQUEST_METHOD', $_SERVER['REQUEST_METHOD']); define('IS_GET', REQUEST_METHOD == 'GET' ? true : false); define('IS_POST', REQUEST_METHOD == 'POST' ? true : false); define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false); define('IS_AJAX', ajax_request()); define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false); alias_import(C('ALIAS')); spl_autoload_register(array(__CLASS__, 'autoload')); set_error_handler(array(__CLASS__, 'error'), E_ALL); set_exception_handler(array(__CLASS__, 'exception')); register_shutdown_function(array(__CLASS__, 'fatalError')); HDPHP::autoLoadFile(); } static private function autoLoadFile() { $files = C('AUTO_LOAD_FILE'); if (is_array($files) && !empty($files)) { foreach ($files as $file) { require_array(array( MODULE_LIB_PATH . $file, APP_LIB_PATH . $file )) || require_cache($file); } } } static public function autoload($className) { $class = ucfirst($className) . '.class.php'; if (substr($className, -5) == 'Model' && require_array(array( HDPHP_DRIVER_PATH . 'Model/' . $class, MODULE_MODEL_PATH . $class, APP_MODEL_PATH . $class ))) {return; } elseif (substr($className, -10) == 'Controller' && require_array(array( HDPHP_CORE_PATH . $class, MODULE_CONTROLLER_PATH . $class, APP_CONTROLLER_PATH . $class ))) {return; } elseif (substr($className, 0, 2) == 'Db' && require_array(array( HDPHP_DRIVER_PATH . 'Db/' . $class ))) { return; } elseif (substr($className, 0, 5) == 'Cache' && require_array(array( HDPHP_DRIVER_PATH . 'Cache/' . $class ))) {return; } elseif (substr($className, 0, 4) == 'View' && require_array(array( HDPHP_DRIVER_PATH . 'View/' . $class, ))) {return; } elseif (substr($className, -4) == 'Hook' && require_array(array( MODULE_HOOK_PATH . $class, APP_HOOK_PATH . $class ))) {return; } elseif (substr($className, -5) == 'Addon' && require_array(array( APP_ADDON_PATH . $class ))) {return; } elseif (substr($className, -3) == 'Tag' && require_array(array( APP_TAG_PATH . $class, MODULE_TAG_PATH . $class ))) { return; } elseif (substr($className, -7) == 'Storage' && require_array(array( HDPHP_DRIVER_PATH . 'Storage/' . $class ))) {return; } elseif (alias_import($className)) { return; } elseif (require_array(array( MODULE_LIB_PATH . $class, APP_LIB_PATH . $class, HDPHP_CORE_PATH . $class, HDPHP_EXTEND_PATH . '/Tool/' . $class )) ) { return; } } static public function exception($e) { halt($e->__toString()); } static public function error($errno, $error, $file, $line) { switch ($errno) { case E_ERROR: case E_PARSE: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: ob_end_clean(); $msg = $error. $file . " 第 $line 行."; if(C('LOG_RECORD')) Log::write("[$errno] " . $msg, Log::ERROR); function_exists('halt') ? halt($msg) : exit('ERROR:' . $msg); break; default: $errorStr = "[$errno] $error " . $file . " 第 $line 行."; trace($errorStr, 'NOTICE', true); if (DEBUG && C('SHOW_NOTICE')) require HDPHP_PATH . 'Lib/Tpl/notice.html'; break; } } static public function fatalError() { if(function_exists('error_get_last')){ if ( $e = error_get_last()) { self::error($e['type'], $e['message'], $e['file'], $e['line']); } } } }final class HdException extends Exception { private $type; private $extra; public function __construct($message, $code = 0, $extra = false) { parent::__construct($message, $code); $this->type = get_class($this); $this->extra = $extra; } public function __toString() { $trace = $this->getTrace(); $this->class = isset($trace[0]['class']) ? $trace[0]['class'] : ''; $this->function = isset($trace[0]['function']) ? $trace[0]['function'] : ''; $this->file = isset($trace[0]['file']) ? $trace[0]['file'] : ''; $this->line = isset($trace[0]['line']) ? $trace[0]['line'] : ''; $traceInfo = ''; $time = date('y-m-d H:i:m'); foreach ($trace as $t) { if (isset($t['file'])) { $traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') '; if (isset($t['class'])) { $traceInfo .= $t['class'] . $t['type'] . $t['function']; } $traceInfo .= "\n"; } } $error['message'] = $this->message; $error['type'] = $this->type; $error['class'] = $this->class; $error['function'] = $this->function; $error['file'] = $this->file; $error['line'] = $this->line; $error['trace'] = $traceInfo; if (C('LOG_EXCEPTION_RECORD')) { Log::Write('(' . $this->type . ') ' . $this->message); } return $error; } }class Log { const FATAL = 'FATAL'; const ERROR = 'ERROR'; const WARNING = 'WARNING'; const NOTICE = 'NOTICE'; const DEBUG = 'DEBUG'; const SQL = 'SQL'; static $log = array(); static public function record($message, $level = self::ERROR, $record = false) { if ($record || in_array($level, C('LOG_LEVEL'))) { self::$log[] = date("[ c ]") . "{$level}: {$message}\r\n"; } } static public function save($type = 3, $destination = NULL, $extraHeaders = NULL) { if (empty(self::$log)) return; if (is_null($destination)) { $destination = APP_LOG_PATH . date("Y_m_d") . ".log"; } if (is_dir(APP_LOG_PATH)) error_log(implode("", self::$log) . "\r\n", $type, $destination, $extraHeaders); self::$log = array(); } static public function write($message, $level = self::ERROR, $type = 3, $destination = NULL, $extraHeaders = NULL) { if (is_null($destination)) { $destination = APP_LOG_PATH . date("Y_m_d") . ".log"; } if (is_dir(APP_LOG_PATH)) error_log(date("[ c ]") . "{$level}: {$message}\r\n", $type, $destination, $extraHeaders); } }final class Route { static public function parseUrl() { if (C('URL_TYPE') == 3 && isset($_GET[C("PATHINFO_VAR")])) { $query = $_GET[C("PATHINFO_VAR")]; } else if (C('URL_TYPE') == 1 && isset($_SERVER['PATH_INFO'])) { $query = $_SERVER['PATH_INFO']; } else if (isset($_SERVER['PATH_INFO'])) { $query = $_SERVER['PATH_INFO']; } else { $query = $_SERVER['QUERY_STRING']; } $url = self::parseRoute($query); $gets = ''; if ((C('URL_TYPE') == 1 && isset($_SERVER['PATH_INFO'])) || (C('URL_TYPE') == 3 && isset($_GET[C("PATHINFO_VAR")]))) { $url = str_replace(array('&', '='), C("PATHINFO_DLI"), $url); $args = explode(C("PATHINFO_DLI"), $url); if (empty($args[0])) { $_GET[C("VAR_MODULE")] = C("DEFAULT_MODULE"); } else { if ($args[0] == C("VAR_MODULE")) { $_GET[$args[0]] = $args[1]; array_shift($args); array_shift($args); } else { $_GET[C("VAR_MODULE")] = $args[0]; array_shift($args); } } if (empty($args[0])) { $_GET[C('VAR_CONTROLLER')] = C('DEFAULT_CONTROLLER'); } else { if ($args[0] == C('VAR_CONTROLLER')) { $_GET[$args[0]] = $args[1]; array_shift($args); array_shift($args); } else { $_GET[C('VAR_CONTROLLER')] = $args[0]; array_shift($args); } } if (empty($args[0])) { $_GET[C('VAR_ACTION')] = C('DEFAULT_ACTION'); } else { if ($args[0] == C('VAR_ACTION')) { $_GET[$args[0]] = $args[1]; array_shift($args); array_shift($args); } else { $_GET[C('VAR_ACTION')] = $args[0]; array_shift($args); } } if (!empty($args[0]) && count($args) % 2 == 0) { $count = count($args); for ($i = 0; $i < $count;) { $_GET[$args [$i]] = isset($args [$i + 1]) ? $args [$i + 1] : ''; $i += 2; } } } else { parse_str($url, $gets); $_GET = array_merge($_GET, $gets); if (!isset($_GET[C("VAR_MODULE")])) { $_GET[C("VAR_MODULE")] = C("DEFAULT_MODULE"); } if (!isset($_GET[C("VAR_CONTROLLER")])) { $_GET[C('VAR_CONTROLLER')] = C('DEFAULT_CONTROLLER'); } if (!isset($_GET[C("VAR_ACTION")])) { $_GET[C('VAR_ACTION')] = C('DEFAULT_ACTION'); } } $_GET[C('VAR_MODULE')] = ucwords($_GET[C('VAR_MODULE')]); $_GET[C('VAR_CONTROLLER')] = str_replace('!', '', ucwords(str_replace('_', '!', $_GET[C('VAR_CONTROLLER')]))); if (C('URL_TYPE') == 2) { unset($_GET[C('PATHINFO_VAR')]); } $_REQUEST = array_merge($_REQUEST, $_GET); self::setConst(); } static private function setConst() { $host = $_SERVER['HTTP_HOST'] ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']; defined('__HOST__') or define("__HOST__", C("HTTPS") ? "https://" : "http://" . $host); $script_file = rtrim($_SERVER['SCRIPT_NAME'], '/'); $root = rtrim(dirname($script_file), '/'); defined('__ROOT__') or define("__ROOT__", __HOST__ . ($root == '/' || $root == '\\' ? '' : $root)); if (C('URL_REWRITE')) { $scriptName = preg_replace('/\/?[a-z]+\.php/i', '', $_SERVER['SCRIPT_NAME']); defined('__WEB__') or define("__WEB__", __HOST__ . $scriptName); } else { defined('__WEB__') or define("__WEB__", __HOST__ . $_SERVER['SCRIPT_NAME']); } defined('__URL__') or define("__URL__", __HOST__ . '/' . trim($_SERVER['REQUEST_URI'], '/')); defined('__APP__') or define("__APP__", __ROOT__ . '/' . basename(APP_PATH)); defined('__COMMON__') or define("__COMMON__", __APP__ . '/Common'); defined('__HDPHP__') or define("__HDPHP__", __HOST__ . '/' . trim(str_ireplace(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']), "", HDPHP_PATH), '/')); defined('__HDPHP_DATA__') or define("__HDPHP_DATA__", __HDPHP__ . '/Data'); defined('__HDPHP_EXTEND__') or define("__HDPHP_EXTEND__", __HDPHP__ . '/Extend'); defined('APP') or define('APP', basename(APP_PATH)); defined('MODULE') or define("MODULE", ucfirst($_GET[C('VAR_MODULE')])); defined('CONTROLLER') or define("CONTROLLER", ucfirst($_GET[C('VAR_CONTROLLER')])); defined('ACTION') or define("ACTION", $_GET[C('VAR_ACTION')]); switch (C("URL_TYPE")) { case 2: defined('__MODULE__') or define("__MODULE__", __WEB__ . '?' . C('VAR_MODULE') . '=' . MODULE); defined('__CONTROLLER__') or define("__CONTROLLER__", __MODULE__ . '&' . C('VAR_CONTROLLER') . '=' . CONTROLLER); defined('__ACTION__') or define("__ACTION__", __CONTROLLER__ . '&' . C('VAR_ACTION') . '=' . ACTION); break; case 3: defined('__MODULE__') or define("__MODULE__", __WEB__ . '?' . C("PATHINFO_VAR") . '=/' . MODULE); defined('__CONTROLLER__') or define("__CONTROLLER__", __MODULE__ . '/' . CONTROLLER); defined('__ACTION__') or define("__ACTION__", __CONTROLLER__ . '/' . ACTION); break; case 1: default: defined('__MODULE__') or define("__MODULE__", __WEB__ . '/' . MODULE); defined('__CONTROLLER__') or define("__CONTROLLER__", __MODULE__ . '/' . CONTROLLER); defined('__ACTION__') or define("__ACTION__", __CONTROLLER__ . '/' . ACTION); break; } } static private function parseRoute($query) { $query = str_ireplace(C('HTML_SUFFIX'), '', trim($query, '/')); $route = C("ROUTE"); if (!$route or !is_array($route)) return $query; foreach ($route as $k => $v) { if (preg_match("@^/.*/[isUx]*$@i", $k)) { if (preg_match($k, $query)) { $v = str_replace('#', '\\', $v); return preg_replace($k, $v, $query); } continue; } $search = array( '@(:year)@i', '@(:month)@i', '@(:day)@i', '@(:num)@i', '@(:any)@i', '@(:[a-z0-9]+\\\d)@i', '@(:[a-z0-9]+\\\w)@i', '@(:[a-z0-9]+)@i' ); $replace = array( '\d{4}', '\d{1,2}', '\d{1,2}', '\d+', '.+', '\d+', '\w+', '([a-z0-9]+)' ); $base_preg = "@^" . preg_replace($search, $replace, $k) . "$@i"; if (!preg_match($base_preg, $query)) { continue; } if (!strstr($k, ":")) { return $v; } $vars = ""; preg_match('/[^:\sa-z0-9]/i', $k, $vars); if (isset($vars[0])) { $roles_ex = explode($vars[0], $k); $url_args = explode($vars[0], $query); } else { $roles_ex = array($k); $url_args = array($query); } $query = $v; foreach ($roles_ex as $m => $n) { if (!strstr($n, ":")) { continue; } $_GET[str_replace(":", "", $n)] = $url_args[$m]; } return $query; } return $query; } static public function toUrl($url) { $route = C("route"); if (!$route) { return $url; } foreach ($route as $routeKey => $routeVal) { $routeKey = trim($routeKey); if (substr($routeKey, 0, 1) === '/') { $regGroup = array(); preg_match_all("@\(.*?\)@i", $routeKey, $regGroup, PREG_PATTERN_ORDER); $searchRegExp = $routeVal; for ($i = 0, $total = count($regGroup[0]); $i < $total; $i++) { $searchRegExp = str_replace('#' . ($i + 1), $regGroup[0][$i], $searchRegExp); } $urlArgs = array(); preg_match_all("@^" . $searchRegExp . "$@i", $url, $urlArgs, PREG_SET_ORDER); if ($urlArgs) { $routeUrl = trim(preg_replace(array('@/\^@', '@/[isUx]$@', '@\$@'), array('', '', ''), $routeKey), '/'); foreach ($regGroup[0] as $k => $v) { $v = preg_replace('@([\*\$\(\)\+\?\[\]\{\}\\\])@', '\\\$1', $v); $routeUrl = preg_replace('@' . $v . '@', $urlArgs[0][$k + 1], $routeUrl, $count = 1); } return trim($routeUrl, '/'); } } else { $routeGetVars = array(); preg_match_all('/:([a-z]*)/i', $routeKey, $routeGetVars, PREG_PATTERN_ORDER); $getRouteUrl = $routeVal; switch (C("URL_TYPE")) { case 1: $getRouteUrl .= '/'; foreach ($routeGetVars[1] as $getK => $getV) { $getRouteUrl .= $getV . '/(.*)/'; } $getRouteUrl = '@' . trim($getRouteUrl, '/') . '@i'; break; case 2: $getRouteUrl .= '&'; foreach ($routeGetVars[1] as $getK => $getV) { $getRouteUrl .= $getV . '=(.*)' . '&'; } $getRouteUrl = '@' . trim($getRouteUrl, '&') . '@i'; break; } $getArgs = array(); preg_match_all($getRouteUrl, $url, $getArgs, PREG_SET_ORDER); if ($getArgs) { $newUrl = $routeKey; foreach ($routeGetVars[0] as $rk => $getName) { $newUrl = str_replace($getName, $getArgs[0][$rk + 1], $newUrl); } return $newUrl; } } } return $url; } static public function removeUrlParam($var, $url = null) { if (is_null($url)) { $url = __URL__; } $url = C('URL_TYPE') == 2 ? $url . '&' : $url . C("PATHINFO_DLI"); switch (C('URL_TYPE')) { case 2: $url = preg_replace(array("/$var=.*?&/", "/&&/"), '', $url); break; default: $url = preg_replace(array("/{$var}{$dli}.*?{$dli}/"), '', $url); } return rtrim($url, "&" . $dli); } static public function getUrl($path, $args = array()) { if (preg_match('/^https?:\/\//', $path)) { return $path; } $root = C('URL_REWRITE') ? preg_replace('/\/?[a-z]+\.php/i', '', __WEB__) : __WEB__; switch (C("URL_TYPE")) { case 1: $root .= '/'; break; case 2: $root .= C('URL_REWRITE') ? '/' : '?'; break; case 3: $root .= (C('URL_REWRITE') ? '/' : '?') . C('PATHINFO_VAR') . '='; break; } if (preg_match('@[^\w/]@i', $path)) { return $root . Route::toUrl($path) . C('HTML_SUFFIX'); } else { $action = array(); $info = explode('/', $path); if (count($info) > 3) { $param = array_slice($info, 3); $info = array_slice($info, 0, 3); for ($i = 0; $i < count($param); $i += 2) { $args[$param[$i]] = $param[$i + 1]; } } switch (count($info)) { case 3: $action[C("VAR_MODULE")] = ucfirst($info[0]); $action[C("VAR_CONTROLLER")] = ucfirst($info[1]); $action[C("VAR_ACTION")] = $info[2]; break; case 2: $action[C("VAR_MODULE")] = ucfirst(MODULE); $action[C("VAR_CONTROLLER")] = ucfirst($info[0]); $action[C("VAR_ACTION")] = $info[1]; break; case 1: $action[C("VAR_MODULE")] = ucfirst(MODULE); $action[C("VAR_CONTROLLER")] = ucfirst(CONTROLLER); $action[C("VAR_ACTION")] = $info[0]; break; default: } switch (C("URL_TYPE")) { case 1: case 3: $url = $action[C("VAR_MODULE")] . '/' . $action[C("VAR_CONTROLLER")] . '/' . $action[C("VAR_ACTION")]; break; case 2: $url = C("VAR_MODULE") . '=' . $action[C("VAR_MODULE")] . '&' . C("VAR_CONTROLLER") . '=' . $action[C("VAR_CONTROLLER")] . '&' . C("VAR_ACTION") . '=' . $action[C("VAR_ACTION")]; break; } if (is_string($args)) { parse_str($args, $args); } if (!empty($args)) { switch (C("URL_TYPE")) { case 1: case 3: foreach ($args as $name => $value) { $url .= '/' . $name . '/' . $value; } break; case 2: foreach ($args as $name => $value) { $url .= '&' . $name . '=' . $value; } break; } } return $root . Route::toUrl($url) . C('HTML_SUFFIX'); } } }function M($table = null, $full = null, $param = array(), $driver = null) { return new Model($table, $full, $param, $driver); } function K($name, $full = null, $param = array(), $driver = null) { $class = ucfirst($name) . "Model"; return new $class(strtolower($name), $full, $param); } function R($tableName = null, $full = null) { return new RelationModel($tableName, $full); } function V($table = null, $full = null) { return new ViewModel($table, $full); } function F($name, $value = false, $path = APP_CACHE_PATH) { static $_cache = array(); $cacheFile = rtrim($path, '/') . '/' . $name . '.php'; if (is_null($value)) { if (is_file($cacheFile)) { unlink($cacheFile); unset($_cache[$name]); } return true; } if ($value === false) { if (isset($_cache[$name])) return $_cache[$name]; return is_file($cacheFile) ? include $cacheFile : null; } $data = "<?php if(!defined('HDPHP_PATH'))exit;\nreturn " . compress(var_export($value, true)) . ";\n?>"; is_dir($path) || dir_create($path); if (!file_put_contents($cacheFile, $data)) { return false; } $_cache[$name] = $value; return true; } function S($name, $value = false, $expire = null, $options = array()) { static $_data = array(); $cacheObj = Cache::init($options); if (is_null($value)) { return $cacheObj->del($name); } $driver = isset($options['Driver']) ? $options['Driver'] : ''; $key = $name . $driver; if ($value === false) { if (isset($_data[$key])) { Debug::$cache['read_s']++; return $_data[$key]; } else { return $cacheObj->get($name, $expire); } } $cacheObj->set($name, $value, $expire); $_data[$key] = $value; return true; } function A($arg, $args = array()) { $arg = str_replace('.', '/', $arg); $pathArr = explode('/', $arg); switch (count($pathArr)) { case 1 : $base = APP_CONTROLLER_PATH . CONTROLLER; $method = $pathArr[0]; break; case 2 : $base = APP_CONTROLLER_PATH . $pathArr[0]; $method = $pathArr[1]; break; case 3 : $base = MODULE_PATH . '../' . $pathArr[0] . '/Controller/' . $pathArr[1]; $method = $pathArr[2]; break; } $class = basename($base) . C('CONTROLLER_FIX'); if (require_cache($base . C('CONTROLLER_FIX') . '.class.php')) { if (class_exists($class)) { $obj = new $class(); if (method_exists($class, $method)) { if (empty($args)) { return $obj->$method(); } else { return call_user_func_array(array(&$obj, $method), $args); } } } } } function import($class = null, $base = null, $ext = ".class.php") { $class = str_replace(".", "/", $class); if (is_null($base)) { $info = explode("/", $class); if ($info[0] == '@') { $base = APP_PATH; $class = substr_replace($class, '', 0, strlen($info[0]) + 1); } elseif (strtoupper($info[0]) == 'HDPHP') { $base = dirname(substr_replace($class, HDPHP_PATH, 0, 6)) . '/'; $class = basename($class); } elseif (in_array($info[0], array("Lib", "Tag"))) { $base = MODULE_PATH; } else { $base = dirname($class) . '/'; $class = basename($class); } } else { $base = str_replace('.', '/', $base); } $file = $base . $class . $ext; if (!class_exists(basename($class), false)) { return require_cache($file); } return true; } function require_cache($path = null) { static $_files = array(); if (is_null($path)) { return $_files; } if (isset($_files[$path])) { return true; } if (!file_exists_case($path)) { return false; } require($path); $_files[$path] = true; return true; } function O($class, $method = null, $args = array()) { $tmp = explode(".", $class); $class = array_pop($tmp); if (!class_exists($class)) { $path = $tmp ? implode('.', $tmp) : null; import($class, $path); } if (class_exists($class, false)) { $obj = new $class(); if (!is_object($obj)) return false; if ($method && method_exists($obj, $method)) { if (empty($args)) { $args = array(); } return call_user_func_array(array($obj, $method), $args); } else { return $obj; } } } function getControl($Control) { return new $Control; } function controller($class, $method = NULl, $args = array()) { $class = $class . C('CONTROLLER_FIX'); $classFile = $class . '.class.php'; if (require_array(array(HDPHP_CORE_PATH . $classFile, MODULE_CONTROLLER_PATH . $classFile, APP_CONTROLLER_PATH . $classFile))) { if (class_exists($class)) { $obj = new $class(); if ($method && method_exists($obj, $method)) { return call_user_func_array(array(&$obj, $method), $args); } return $obj; } } else { return false; } } function session($name = '', $value = '') { if (is_array($name)) { ini_set('session.auto_start', 0); if (isset($name['name'])) session_name($name['name']); if (isset($_REQUEST[session_name()])) session_id($_REQUEST[session_name()]); if (isset($name['path'])) session_save_path($name['path']); if (isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']); if (isset($name['expire'])) { ini_set('session.gc_maxlifetime', $name['expire']); session_set_cookie_params($name['expire']); } if (isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid'] ? 1 : 0); if (isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies'] ? 1 : 0); if (isset($name['cache_limiter'])) session_cache_limiter($name['cache_limiter']); if (isset($name['cache_expire'])) session_cache_expire($name['cache_expire']); if (isset($name['type'])) { $class = 'Session' . ucwords($name['type']); require_cache(HDPHP_DRIVER_PATH . '/Session/' . $class . '.class.php'); $hander = new $class(); $hander->run(); } if (C("SESSION_AUTO_START")) { session_start(); } } elseif ($name === '') { return $_SESSION; } elseif (is_null($name)) { $_SESSION = array(); session_unset(); session_destroy(); } elseif ($value === '') { if ('[pause]' == $name) { session_write_close(); } elseif ('[start]' == $name) { session_start(); } elseif ('[destroy]' == $name) { $_SESSION = array(); session_unset(); session_destroy(); } elseif ('[regenerate]' == $name) { session_regenerate_id(); } elseif (0 === strpos($name, '?')) { $name = substr($name, 1); return isset($_SESSION[$name]); } elseif (is_null($name)) { $_SESSION = array(); } else { return isset($_SESSION[$name]) ? $_SESSION[$name] : null; } } elseif (is_null($value)) { if (isset($_SESSION[$name])) unset($_SESSION[$name]); } else { $_SESSION[$name] = $value; } } function cookie($name, $value = '', $option = array()) { $config = array('prefix' => C('COOKIE_PREFIX'), 'expire' => C('COOKIE_EXPIRE'), 'path' => C('COOKIE_PATH'), 'domain' => C('COOKIE_DOMAIN'), ); if (!empty($option)) { if (is_numeric($option)) $option = array('expire' => $option); elseif (is_string($option)) parse_str($option, $option); $config = array_merge($config, array_change_key_case($option)); } if (is_null($name)) { if (empty($_COOKIE)) return; $prefix = empty($value) ? $config['prefix'] : $value; if (!empty($prefix)) { foreach ($_COOKIE as $key => $val) { if (0 === stripos($key, $prefix)) { setcookie($key, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$key]); } } } return $_COOKIE; } $name = $config['prefix'] . $name; if ('' === $value) { return isset($_COOKIE[$name]) ? json_decode(MAGIC_QUOTES_GPC ? stripslashes($_COOKIE[$name]) : $_COOKIE[$name]) : null; } else { if (is_null($value)) { setcookie($name, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$name]); } else { $value = json_encode($value); $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0; setcookie($name, $value, $expire, $config['path'], $config['domain']); $_COOKIE[$name] = $value; } } } function browser_info() { $agent = strtolower($_SERVER["HTTP_USER_AGENT"]); $browser = null; if (strstr($agent, 'msie 9.0')) { $browser = 'msie9'; } else if (strstr($agent, 'msie 8.0')) { $browser = 'msie8'; } else if (strstr($agent, 'msie 7.0')) { $browser = 'msie7'; } else if (strstr($agent, 'msie 6.0')) { $browser = 'msie6'; } else if (strstr($agent, 'firefox')) { $browser = 'firefox'; } else if (strstr($agent, 'chrome')) { $browser = 'chrome'; } else if (strstr($agent, 'safari')) { $browser = 'safari'; } else if (strstr($agent, 'opera')) { $browser = 'opera'; } return $browser; } function C($name = null, $value = null) { static $config = array(); if (is_null($name)) { return $config; } else if (is_string($name)) { $name = strtoupper($name); $data = array_change_key_case($config, CASE_UPPER); if (!strstr($name, '.')) { if (is_null($value)) { return isset($data[$name]) ? $data[$name] : null; } else { return $config[$name] = isset($data[$name]) && is_array($data[$name]) && is_array($value) ? array_merge($config[$name], $value) : $value; } } else { $name = array_change_key_case(explode(".", $name)); if (is_null($value)) { return isset($data[$name[0]][$name[1]]) ? $data[$name[0]][$name[1]] : null; } else { return $config[$name[0]][$name[1]] = $value; } } } else if (is_array($name)) { return $config = array_merge($config, array_change_key_case($name, CASE_UPPER)); } } function L($name = null, $value = null) { static $languge = array(); if (is_null($name)) { return $languge; } if (is_string($name)) { $name = strtolower($name); if (!strstr($name, '.')) { if (is_null($value)) return isset($languge[$name]) ? $languge[$name] : null; $languge[$name] = $value; return $languge[$name]; } $name = array_change_key_case_d(explode(".", $name), 0); if (is_null($value)) { return isset($languge[$name[0]][$name[1]]) ? $languge[$name[0]][$name[1]] : null; } $languge[$name[0]][$name[1]] = $value; } if (is_array($name)) { $languge = array_merge($languge, array_change_key_case_d($name)); return true; } } function Q($var, $default = null, $filter = null) { $var = explode(".", $var); if (count($var) == 1) { array_unshift($var, 'request'); } $var[0] = strtolower($var[0]); switch (strtolower($var[0])) { case 'get' : $data = &$_GET; break; case 'post' : $data = &$_POST; break; case 'request' : $data = &$_REQUEST; break; case 'files' : $data = &$_FILES; break; case 'session' : $data = &$_SESSION; break; case 'cookie' : $data = &$_COOKIE; break; case 'server' : $data = &$_SERVER; break; case 'globals' : $data = &$GLOBALS; break; default : throw_exception($var[0] . 'Q方法参数错误'); } if (empty($var[1])) { return $data; } else if (isset($data[$var[1]])) { $value = $data[$var[1]]; $funcArr = is_null($filter) ? C("FILTER_FUNCTION") : $filter; if (is_string($funcArr) && !empty($funcArr)) { $funcArr = explode(",", $funcArr); } if (!empty($funcArr) && is_array($funcArr)) { foreach ($funcArr as $func) { if (!function_exists($func)) continue; $value = is_array($value) ? array_map($func, $value) : $func($value); } $data[$var[1]] = $value; return $value; } return $value; } else { $data[$var[1]] = $default; return $default; } } function p($var) { if (is_bool($var)) { var_dump($var); } else if (is_null($var)) { var_dump(NULL); } else { echo "<pre style='position:relative;z-index:1000;padding:10px;border-radius:5px;background:#F5F5F5;border:1px solid #aaa;font-size:14px;line-height:18px;opacity:0.9;'>" . print_r($var, true) . "</pre>"; } } function go($url, $time = 0, $msg = '') { $url = Route::getUrl($url); if (!headers_sent()) { $time == 0 ? header("Location:" . $url) : header("refresh:{$time};url={$url}"); exit($msg); } else { echo "<meta http-equiv='Refresh' content='{$time};URL={$url}'>"; if ($time) exit($msg); } } function runtime($start, $end = '', $decimals = 3) { static $runtime = array(); if ($end != '') { $runtime [$end] = microtime(); return number_format($runtime [$end] - $runtime [$start], $decimals); } $runtime [$start] = microtime(); } function ip_get_client($type = 0) { $type = intval($type); if (isset($_SERVER)) { if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) { $ip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } else if (isset($_SERVER["HTTP_CLIENT_IP"])) { $ip = $_SERVER["HTTP_CLIENT_IP"]; } else { $ip = $_SERVER["REMOTE_ADDR"]; } } else { if (getenv("HTTP_X_FORWARDED_FOR")) { $ip = getenv("HTTP_X_FORWARDED_FOR"); } else if (getenv("HTTP_CLIENT_IP")) { $ip = getenv("HTTP_CLIENT_IP"); } else { $ip = getenv("REMOTE_ADDR"); } } $long = ip2long($ip); $clientIp = $long ? array($ip, $long) : array("0.0.0.0", 0); return $clientIp[$type]; } function ajax_request() { if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') return true; return false; } function addslashes_d($data) { if (is_string($data)) { return addslashes($data); } if (is_numeric($data)) { return $data; } if (is_array($data)) { $var = array(); foreach ($data as $k => $v) { if (is_array($v)) { $var[$k] = addslashes_d($v); continue; } else { $var[$k] = addslashes($v); } } return $var; } } function stripslashes_d($data) { if (empty($data)) { return $data; } elseif (is_string($data)) { return stripslashes($data); } elseif (is_array($data)) { $var = array(); foreach ($data as $k => $v) { if (is_array($v)) { $var[$k] = stripslashes_d($v); continue; } else { $var[$k] = stripslashes($v); } } return $var; } } function array_to_String($array, $level = 0) { if (!is_array($array)) { return "'" . $array . "'"; } $space = ''; for ($i = 0; $i <= $level; $i++) { $space .= "\t"; } $arr = "Array\n$space(\n"; $c = $space; foreach ($array as $k => $v) { $k = is_string($k) ? '\'' . addcslashes($k, '\'\\') . '\'' : $k; $v = !is_array($v) && (!preg_match("/^\-?[1-9]\d*$/", $v) || strlen($v) > 12) ? '\'' . addcslashes($v, '\'\\') . '\'' : $v; if (is_array($v)) { $arr .= "$c$k=>" . array_to_String($v, $level + 1); } else { $arr .= "$c$k=>$v"; } $c = ",\n$space"; } $arr .= "\n$space)"; return $arr; } if (!function_exists('json_encode')) { function json_encode($value) { $json = new json(); return $json->encode($value); } } if (!function_exists('json_decode')) { function json_decode($json_value, $bool = false) { $json = new json(); return $json->decode($json_value, $bool); } } function mobile_area($mobile) { require_cache(HDPHP_EXTEND_PATH . "Org/Mobile/Mobile.class.php"); return Mobile::area($mobile); } if (!function_exists('image_type_to_extension')) { function image_type_to_extension($type, $dot = true) { $e = array(1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp', 'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc', 'aiff', 'wbmp', 'xbm'); $type = (int)$type; return ($dot ? '.' : '') . $e[$type]; } } function rand_str($len = 6) { $data = 'abcdefghijklmnopqrstuvwxyz0123456789'; $str = ''; while (strlen($str) < $len) $str .= substr($data, mt_rand(0, strlen($data) - 1), 1); return $str; } function encrypt($data, $key = null) { return encry::encrypt($data, $key); } function decrypt($data, $key = null) { return encry::decrypt($data, $key); } function data_format(&$data, $func = null) { $functions = is_null($func) ? C("FILTER_FUNCTION") : $func; if (!is_array($functions)) { $functions = preg_split("/\s*,\s*/", $functions); } foreach ($functions as $_func) { if (is_string($data)) { $data = $_func($data); } else if (is_array($data)) { foreach ($data as $k => $d) { $data[$k] = is_array($d) ? data_format($d, $functions) : $_func($d); } } } return $data; } function _default($varName, $value = "") { return empty($varName) ? $value : $varName; } function _request($method, $varName = null, $html = true) { $method = strtolower($method); switch ($method) { case 'ispost' : case 'isget' : case 'ishead' : case 'isdelete' : case 'isput' : return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method, 2)); case 'get' : $data = &$_GET; break; case 'post' : $data = &$_POST; break; case 'request' : $data = &$_REQUEST; break; case 'Session' : $data = &$_SESSION; break; case 'cookie' : $data = &$_COOKIE; break; case 'server' : $data = &$_SERVER; break; case 'globals' : $data = &$GLOBALS; break; default : throw_exception('abc'); } if (is_null($varName)) return $data; if (isset($data[$varName]) && $html) { $data[$varName] = htmlspecialchars($data[$varName]); } return isset($data[$varName]) ? $data[$varName] : null; } function set_http_state($code) { $state = array(200 => 'OK', 301 => 'Moved Permanently', 302 => 'Moved Temporarily ', 400 => 'Bad Request', 403 => 'Forbidden', 404 => 'Not Found', 500 => 'Internal Server Error', 503 => 'Service Unavailable', ); if (isset($state[$code])) { header('HTTP/1.1 ' . $code . ' ' . $state[$code]); header('Status:' . $code . ' ' . $state[$code]); } } function is_ssl() { if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) { return true; } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) { return true; } return false; } function print_const() { $define = get_defined_constants(true); foreach ($define['user'] as $k => $d) { $const[$k] = $d; } p($const); } function date_before($time, $unit = null) { $time = intval($time); $unit = is_null($unit) ? array("年", "月", "星期", "天", "小时", "分钟", "秒") : $unit; switch (true) { case $time < (NOW - 31536000) : return floor((NOW - $time) / 31536000) . $unit[0] . '前'; case $time < (NOW - 2592000) : return floor((NOW - $time) / 2592000) . $unit[1] . '前'; case $time < (NOW - 604800) : return floor((NOW - $time) / 604800) . $unit[2] . '前'; case $time < (NOW - 86400) : return floor((NOW - $time) / 86400) . $unit[3] . '前'; case $time < (NOW - 3600) : return floor((NOW - $time) / 3600) . $unit[4] . '前'; case $time < (NOW - 60) : return floor((NOW - $time) / 60) . $unit[5] . '前'; default : return floor(NOW - $time) . $unit[6] . '前'; } } function get_uuid($sep = '') { if (function_exists('com_create_guid')) { return com_create_guid(); } else { mt_srand((double)microtime() * 10000); $id = strtoupper(md5(uniqid(rand(), true))); $sep = ''; $uuid = substr($id, 0, 8) . $sep . substr($id, 8, 4) . $sep . substr($id, 12, 4) . $sep . substr($id, 16, 4) . $sep . substr($id, 20, 12); return $uuid; } } function U($path, $args = array()) { return Route::getUrl($path, $args); } function addon_url($path, $param = array()) { if (!empty($param)) { $param = '&' . http_build_query($param); } else { $param = ''; } $info = explode('/', $path); switch (count($info)) { case 3: $url = __ROOT__ . "/index.php?g=Addon&m={$info[0]}&c={$info[1]}&a={$info[2]}" . $param; break; case 2: $url = __ROOT__ . "/index.php?g=Addon&m=" . MODULE . "&c={$info[0]}&a={$info[1]}" . $param; break; case 1: $url = __ROOT__ . "/index.php?g=Addon&m=" . MODULE . "&c=" . CONTROLLER . "&a={$info[0]}" . $param; break; } return $url; } function N($name, $num = NULL) { static $data = array(); if (!isset($data[$name])) { $data[$name] = 0; } if (is_null($num)) { return $data[$name]; } else { $data[$name] += (int)$num; } } function md5_d($var) { return md5(serialize($var)); } function hash_hd($data, $len) { $hash = crc32($data) & 0xfffffff; return $hash % $len; } function dir_create($dirName, $auth = 0755) { $dirName = str_replace("\\", "/", $dirName); $dirPath = rtrim($dirName, '/'); if (is_dir($dirPath)) return true; $dirs = explode('/', $dirPath); $dir = ''; foreach ($dirs as $v) { $dir .= $v . '/'; is_dir($dir) or @mkdir($dir, $auth, true); } return is_dir($dirPath); } function hd_date($time, $format = 'Y-m-d') { return date($format, $time); } function hd_substr($string, $len = 20, $end = '...') { $con = mb_substr($string, 0, $len, 'utf-8'); if ($con != $string) { $con .= $end; } return $con; } function load($file) { $file = str_replace(".", "/", preg_replace('@\.php@i', '', $file)); if (!strstr($file, '/')) { $app = LIB_PATH . $file . '.php'; $group = COMMON_LIB_PATH . $file . '.php'; return require_cache($app) || (IS_GROUP && require_cache($group)); } $info = explode('/', $file); if ($info[0] == '@' || APP == $info[0]) { $file = APP_PATH . substr_replace($file, '', 0, strlen($info[0]) + 1); } return require_cache($file); } function alias_import($name = null, $path = null) { static $_alias = array(); if (is_null($name)) { return $_alias; } if (is_array($name)) { $_alias = array_merge($_alias, array_change_key_case($name)); return true; } else if (!is_null($path)) { return $_alias[$name] = $path; } else if (isset($_alias[strtolower($name)])) { return require_cache($_alias[$name]); } return false; } function require_array($fileArr) { foreach ($fileArr as $file) { if (is_file($file) && require_cache($file)) return true; } return false; } function file_exists_case($file) { if (is_file($file)) { if (IS_WIN && C("CHECK_FILE_CASE")) { if (basename(realpath($file)) != basename($file)) { return false; } } return true; } return false; } function remove_url_param($var, $url = null) { return Route::removeUrlParam($var, $url); } function get_size($size, $decimals = 2) { switch (true) { case $size >= pow(1024, 3): return round($size / pow(1024, 3), $decimals) . " GB"; case $size >= pow(1024, 2): return round($size / pow(1024, 2), $decimals) . " MB"; case $size >= pow(1024, 1): return round($size / pow(1024, 1), $decimals) . " KB"; default: return $size . 'B'; } } function array_defined($arr) { foreach ($arr as $k => $v) { $k = strtoupper($k); if (is_string($v)) { define($k, $v); } elseif (is_numeric($v)) { defined($k, $v); } elseif (is_bool($v)) { $v = $v ? 'true' : 'false'; define($k, $v); } } return true; } function array_change_key_case_d($arr, $type = 0) { $function = $type ? 'strtoupper' : 'strtolower'; $newArr = array(); if (!is_array($arr) || empty($arr)) return $newArr; foreach ($arr as $k => $v) { $k = $function($k); if (is_array($v)) { $newArr[$k] = array_change_key_case_d($v, $type); } else { $newArr[$k] = $v; } } return $newArr; } function array_key_exists_d($key, $arr) { return array_key_exists(strtolower($key), array_change_key_case_d($arr)); } function array_to_object($arr) { if (!is_array($arr) || empty($arr)) { return null; } return (object)$arr; } function array_change_value_case($arr, $type = 0) { $function = $type ? 'strtoupper' : 'strtolower'; $newArr = array(); foreach ($arr as $k => $v) { if (is_array($v)) { $newArr[$k] = array_change_value_case($v, $type); } else { $newArr[$k] = $function($v); } } return $newArr; } function file_merge($files, $space = false, $tag = false) { $str = ''; foreach ($files as $file) { $con = trim(file_get_contents($file)); if ($space) $con = compress($con); $str .= substr($con, -2) == '?>' ? trim(substr($con, 5, -2)) : trim($con, 5); } return $tag ? '<?php if(!defined("HDPHP_PATH")){exit("No direct script access allowed");}' . $str . "\t?>" : $str; } function compress($content) { $str = ""; $data = token_get_all($content); $end = false; for ($i = 0, $count = count($data); $i < $count; $i++) { if (is_string($data[$i])) { $end = false; $str .= $data[$i]; } else { switch ($data[$i][0]) { case T_COMMENT: case T_DOC_COMMENT: break; case T_WHITESPACE: if (!$end) { $end = true; $str .= " "; } break; case T_START_HEREDOC: $str .= "<<<HDPHP\n"; break; case T_END_HEREDOC: $str .= "HDPHP;\n"; for ($m = $i + 1; $m < $count; $m++) { if (is_string($data[$m]) && $data[$m] == ';') { $i = $m; break; } if ($data[$m] == T_CLOSE_TAG) { break; } } break; default: $end = false; $str .= $data[$i][1]; } } } return $str; } function get_defines($name = "", $value = null, $type = 'user') { if ($name) { $const = get_defined_constants(); return defined($name) ? $const[$name] : $value; } $const = get_defined_constants(true); return $type === true ? $const : $const[$type]; } function throw_exception($msg, $type = "HdException", $code = 0) { if (class_exists($type, false)) { throw new $type($msg, $code, true); } else { halt($msg); } } function log_write($error) { $trace = debug_backtrace(); $e['message'] = $error; $e['file'] = $trace[0]['file']; $e['line'] = $trace[0]['line']; $e['class'] = isset($trace[0]['class']) ? $trace[0]['class'] : ""; $e['function'] = isset($trace[0]['function']) ? $trace[0]['function'] : ""; $msg = ("[Error]" . $e['message'] . " [Time]" . date("y-m-d h:i") . " [File]" . $e['file'] . " [Line]" . $e['line']); Log::write($msg); } function halt($error) { $e = array(); if (DEBUG) { if (!is_array($error)) { $trace = debug_backtrace(); $e['message'] = $error; $e['file'] = $trace[0]['file']; $e['line'] = $trace[0]['line']; $e['class'] = isset($trace[0]['class']) ? $trace[0]['class'] : ""; $e['function'] = isset($trace[0]['function']) ? $trace[0]['function'] : ""; ob_start(); debug_print_backtrace(); $e['trace'] = htmlspecialchars(ob_get_clean()); } else { $e = $error; } } else { if ($_url = C('ERROR_URL')) { go($_url); } else { $e['message'] = C('ERROR_MESSAGE'); } } require HDPHP_PATH . 'Lib/Tpl/halt.html'; exit; } function error($error) { halt($error); } function trace($value = '[HDPHP]', $level = 'DEBUG', $record = false) { static $_trace = array(); if ('[HDPHP]' === $value) { return $_trace; } else { $info = ' : ' . print_r($value, true); if (DEBUG && 'ERROR' == $level) { throw_exception($info); } if (!isset($_trace[$level])) { $_trace[$level] = array(); } $_trace[$level][] = $info; if (IS_AJAX || $record) { Log::record($info, $level, $record); } } } function _404($msg = "", $url = "") { DEBUG && halt($msg); Log::write($msg); if (empty($url) or C("404_URL")) { $url = C("404_URL"); } if ($url) go($url); else set_http_state(404); exit; } function firephp($data) { ob_start(); $firephp = FirePHP::getInstance(true); $firephp->log($data, 'Iterators'); ob_flush(); ob_clean(); } function FriendlyErrorType($type) { switch ($type) { case E_ERROR: return 'E_ERROR'; case E_WARNING: return 'E_WARNING'; case E_PARSE: return 'E_PARSE'; case E_NOTICE: return 'E_NOTICE'; case E_CORE_ERROR: return 'E_CORE_ERROR'; case E_CORE_WARNING: return 'E_CORE_WARNING'; case E_CORE_ERROR: return 'E_COMPILE_ERROR'; case E_CORE_WARNING: return 'E_COMPILE_WARNING'; case E_USER_ERROR: return 'E_USER_ERROR'; case E_USER_WARNING: return 'E_USER_WARNING'; case E_USER_NOTICE: return 'E_USER_NOTICE'; case E_STRICT: return 'E_STRICT'; case E_RECOVERABLE_ERROR: return 'E_RECOVERABLE_ERROR'; case E_DEPRECATED: return 'E_DEPRECATED'; case E_USER_DEPRECATED: return 'E_USER_DEPRECATED'; } return $type; } function extension_exists($ext) { $ext = strtolower($ext); $loaded_extensions = get_loaded_extensions(); return in_array($ext, array_change_value_case($loaded_extensions, 0)); } function int_to_string(&$data, array $map = array('status' => array('0' => '禁止', '1' => '启用'))) { $map = (array)$map; foreach ($data as $n => $d) { foreach ($map as $name => $m) { if (isset($d[$name]) && isset($m[$d[$name]])) { $data[$n][$name . '_text'] = $m[$d[$name]]; } } } }class Cache { protected $isConnect = false; protected $options = array(); static public function init($options = array()) { return CacheFactory::factory($options); } public function __get($name) { return $this->get($name); } public function __set($name, $value) { return $this->set($name, $value); } public function __call($method, $args) { if (method_exists($this, $method)) { return call_user_func_array(array($this, $method), $args); } return false; } public function __unset($name) { return $this->del($name); } public function options($name, $value = null) { if (!is_null($value)) { $this->options[$name] = $value; return true; } else { if (isset($this->options[$name])) { return $this->options[$name]; } else { return null; } } } protected function queue($name) { static $drivers = array( "file" => "F" ); $driver = isset($this->options['Driver']) ? $this->options['Driver'] : 'file'; $_queue = $drivers[$driver][0]("hdphp_queue"); if (!$_queue) { $_queue = array(); } array_push($_queue, $name); $hdphp_queue = array_unique($_queue); if (count($hdphp_queue) > $this->options['length']) { $gc = array_shift($hdphp_queue); if ($gc) $this->del($gc); } return $drivers[$driver][0]("hdphp_queue", $hdphp_queue); } protected function record($type, $stat = 1) { if (!DEBUG && !C("SHOW_CACHE")) return; if ($type === 1) { $stat ? Debug::$cache['write_s']++ : Debug::$cache['write_f']++; } else { $stat ? Debug::$cache['read_s']++ : Debug::$cache['read_f']++; } } }final class CacheFactory { public static $cacheFactory = null; protected $cacheList = array(); private function __construct() { } public static function factory($options) { $options = is_array($options) ? $options : array(); if (is_null(self::$cacheFactory)) { self::$cacheFactory = new CacheFactory(); } $driver = isset($options['driver']) ? $options['driver'] : C("CACHE_TYPE"); $driverName = md5_d($options); if (isset(self::$cacheFactory->cacheList[$driverName])) { return self::$cacheFactory->cacheList[$driverName]; } $class = 'Cache' . ucwords(strtolower($driver)); if(!class_exists($class)){ $classFile = HDPHP_DRIVER_PATH . 'Cache/' . $class . '.class.php'; if (!require_cache($classFile)) { halt("缓存类型指定错误，不存在缓存驱动文件:" . $classFile); } } $cacheObj = new $class($options); self::$cacheFactory->cacheList[$driverName] = $cacheObj; return self::$cacheFactory->cacheList[$driverName]; } }class CacheFile extends Cache { public function __construct($options = array()) { $this->options['dir'] = isset($options['dir']) ? rtrim($options['dir'], '/') : APP_CACHE_PATH; $this->options['expire'] = isset($options['expire']) ? intval($options['expire']) : C("CACHE_TIME"); $this->options['prefix'] = isset($options['prefix']) ? $options['prefix'] : ''; $this->options['length'] = isset($options['length']) ? $options['length'] : 0; $this->options['zip'] = isset($options['zip']) ? $options['zip'] : false; $this->options['save'] = isset($options['save']) ? $options['save'] : true; $this->isConnect = is_dir($this->options['dir']) && is_writeable($this->options['dir']); if (!$this->isConnect) { $this->createDir(); } } private function createDir() { $this->isConnect = dir_create($this->options['dir']); } protected function getCacheFile($name) { return $this->options['dir'] . '/' . $this->options['prefix'] . $name . ".php"; } public function set($name, $data, $expire = null) { $cacheFile = $this->getCacheFile($name); if (is_null($data)) { if (is_file($cacheFile)) { return unlink($cacheFile); } else { return true; } } $expire = sprintf("%010d", !is_null($expire) ? (int)$expire : $this->options['expire']); if ($expire < 0) return false; if (!$this->isConnect) { $this->createDir(); } $data = serialize($data); if ($this->options['zip'] && function_exists("gzcompress")) { $data = gzcompress($data, 6); } $data = "<?php\n//" . $expire . $data . "\n?>"; $stat = file_put_contents($cacheFile, $data); if ($stat) { if ($this->options['length'] > 0) { $this->queue($name); } $this->record(1, 1); return true; } else { $this->record(1, 0); return false; } } public function get($name) { $cacheFile = $this->getCacheFile($name); if (!is_file($cacheFile)) { $this->record(2, 0); return null; } $content = @file_get_contents($cacheFile); if (!$content) { $this->record(2, 0); return null; } $expire = intval(substr($content, 8, 10)); $mtime = filemtime($cacheFile); if ($expire > 0 && $mtime + $expire < time()) { @unlink($cacheFile); $this->record(2, 0); return false; } $data = substr($content, 18, -3); if ($this->options['zip'] && function_exists("gzuncompress")) { $data = gzuncompress($data); } $this->record(2, 1); return unserialize($data); } public function del($name) { $cacheFile = $this->getCacheFile($name); return is_file($cacheFile) && unlink($cacheFile); } public function delAll($time = null) { foreach (glob($this->options['dir'] . '/*.*') as $file) { if (is_file($file)) { if ($time) { (filemtime($file) + $time < time()) && unlink($file); } else { unlink($file); } } } return true; } }abstract class Db implements DbInterface { public $table = NULL; public $pri = null; public $fieldData; public $lastQuery; public $opt = array( 'table' => null, 'pri' => null, 'field' => '*', 'fieldData' => array(), 'where' => '', 'like' => '', 'group' => '', 'having' => '', 'order' => '', 'limit' => '', 'cacheTime' => null ); public $lastSql; public $error = NULL; protected $condition = array( "eq" => " = ", "neq" => " <> ", "gt" => " > ", "egt" => " >= ", "lt" => " < ", "elt" => " <= ", ); public function link($table, $full) { if ($this->connect()) { if ($table) { $this->table($table, $full); $this->table = $this->opt['table']; $this->fieldData = $this->opt['fieldData']; $this->pri = $this->opt['pri']; } return $this->link; } else { $this->error('数据库连接错误'); } } public function table($table, $full = false) { $this->optInit(); $fieldData = $this->getAllField($table, $full); $pri = $this->getPrimaryKey($table, $full); $this->opt['table'] = $full ? $table : C('DB_PREFIX') . $table; $this->opt['fieldData'] = $fieldData; $this->opt['pri'] = $pri; } public function getAllField($table, $full = false) { if (!$full) { $table = C('DB_PREFIX') . $table; } $name = C('DB_DATABASE') . '.' . $table; if (!DEBUG && F($name, false, APP_TABLE_PATH)) { $fieldData = F($name, false, APP_TABLE_PATH); } else { $sql = "show columns from `$table`"; if (!$result = $this->query($sql)) { return false; } $fieldData = array(); foreach ($result as $res) { $f ['field'] = $res ['Field']; $f ['type'] = $res ['Type']; $f ['null'] = $res ['Null']; $f ['field'] = $res ['Field']; $f ['key'] = ($res ['Key'] == "PRI" && $res['Extra']) || $res ['Key'] == "PRI"; $f ['default'] = $res ['Default']; $f ['extra'] = $res ['Extra']; $fieldData [$res ['Field']] = $f; } DEBUG || F($name, $fieldData, APP_TABLE_PATH); } return $fieldData; } private function getPrimaryKey($table, $full = false) { $fieldData = $this->getAllField($table, $full); $pri = ''; foreach ($fieldData as $field => $v) { if ($v['key'] == 1) { $pri = $field; } } return $pri; } protected function optInit() { $this->cacheTime = -1; $this->error = NULL; $opt = array( 'table' => $this->table, 'pri' => $this->pri, 'field' => '*', 'fieldData' => $this->fieldData, 'where' => '', 'like' => '', 'group' => '', 'having' => '', 'order' => '', 'limit' => '', 'cacheTime' => null, ); return $this->opt = array_merge($this->opt, $opt); } public function getField($field, $returnAll = false) { $this->field($field); $result = $this->select(); if ($result) { $field = explode(',', str_replace(' ', '', $field)); switch (count($field)) { case 1: if ($returnAll) { $data = array(); foreach ($result as $v) { $data[] = current($v); } return $data; } else { return current($result[0]); } case 2: $data = array(); foreach ($result as $v) { $data[$v[$field[0]]] = $v[$field[1]]; } return $data; default: $data = array(); foreach ($result as $v) { $data[$v[$field[0]]] = $v; } return $data; } } else { return array(); } } public function select($where = '') { $this->where($where); $sql = 'SELECT ' . $this->opt['field'] . ' FROM ' . $this->opt['table'] . $this->opt['where'] . $this->opt['group'] . $this->opt['having'] . $this->opt['order'] . $this->opt['limit']; return $this->query($sql); } public function insert($data = array(), $type = 'INSERT') { $value = $this->formatField($data); if (!$value) { $this->optInit(); return false; } $sql = $type . " INTO " . $this->opt['table'] . "(" . implode(',', $value['fields']) . ")" . "VALUES (" . implode(',', $value['values']) . ")"; return $this->exe($sql); } public function replace($data) { return $this->insert($data, 'REPLACE'); } public function update($data = array()) { if (empty($this->opt['where'])) { if (isset($data[$this->opt['pri']])) { $this->opt['where'] = " WHERE " . $this->opt['pri'] . " = " . intval($data[$this->opt['pri']]); } else { return false; } } $data = $this->formatField($data); if (empty($data)) { $this->optInit(); return false; } $sql = "UPDATE " . $this->opt['table'] . " SET "; foreach ($data['fields'] as $n => $field) { $sql .= $field . "=" . $data['values'][$n] . ','; } $sql = trim($sql, ',') . $this->opt['where'] . $this->opt['limit']; return $this->exe($sql); } public function delete($where = '') { $this->where($where); if (empty($this->opt['where'])) { $this->optInit(); return false; } $sql = "DELETE FROM " . $this->opt['table'] . $this->opt['where'] . $this->opt['limit']; return $this->exe($sql); } public function formatField($vars) { $data = array(); foreach ($vars as $k => $v) { if ($this->isField($k)) { $data['fields'][] = "`" . $k . "`"; $v = $this->escapeString($v); $data['values'][] = is_numeric($v) ? $v : "\"$v\""; } } return $data; } public function isField($field) { return isset($this->opt['fieldData'][$field]); } public function where($opt) { $where = ''; if (empty($opt)) { return; } if (is_numeric($opt)) { $where .= ' ' . $this->opt['pri'] . "=$opt "; } else if (is_string($opt)) { $where .= " $opt "; } else if (is_array($opt)) { foreach ($opt as $key => $set) { if ($key[0] == '_') { switch (strtolower($key)) { case '_query': parse_str($set, $q); $this->where($q); break; case '_string': $set = preg_match('@(AND|OR|XOR)\s*$@i', $set) ? $set : $set . ' AND '; $where .= $set; break; } } else if (is_numeric($key)) { if (!preg_match('@(AND|OR|XOR)\s*$@i', $set)) { $set .= isset($opt['_logic']) ? " {$opt['_logic']} " : ' AND '; } $where .= $set; } else if (is_string($key)) { if (!is_array($set)) { $logic = isset($opt['_logic']) ? " {$opt['_logic']} " : ' AND '; $where .= " $key " . "='$set' " . $logic; } else { $logic = isset($opt['_logic']) ? " {$opt['_logic']} " : ' AND '; $logic = isset($set['_logic']) ? " {$set['_logic']} " : $logic; if (is_string(end($set)) && in_array(strtoupper(end($set)), array('AND', 'OR', 'XOR'))) { $logic = ' ' . current($set) . ' '; } reset($set); if (is_array(current($set))) { foreach ($set as $exp) { if (is_array($exp)) { $t[$key] = $exp; $this->where($t); $this->opt['where'] .= strtoupper($logic); } } } else { $option = !is_array($set[1]) ? explode(',', $set[1]) : $set[1]; switch (strtoupper($set[0])) { case 'IN': $value = ''; foreach ($option as $v) { $value .= is_numeric($v) ? $v . "," : "'" . $v . "',"; } $value = trim($value, ','); $where .= " $key " . " IN ($value) $logic"; break; case 'NOTIN': $value = ''; foreach ($option as $v) { $value .= is_numeric($v) ? $v . "," : "'" . $v . "',"; } $value = trim($value, ','); $where .= " $key " . " NOT IN ($value) $logic"; break; case 'BETWEEN': $where .= " $key " . " BETWEEN " . $option[0] . ' AND ' . $option[1] . $logic; break; case 'NOTBETWEEN': $where .= " $key " . " NOT BETWEEN " . $option[0] . ' AND ' . $option[1] . $logic; break; case 'LIKE': foreach ($option as $v) { $where .= " $key " . " LIKE '$v' " . $logic; } break; case 'NOTLIKE': foreach ($option as $v) { $where .= " $key " . " NOT LIKE '$v'" . $logic; } break; case 'EQ': $where .= " $key " . '=' . (is_numeric($set[1]) ? $set[1] : "'{$set[1]}'") . $logic; break; case 'NEQ': $where .= " $key " . '<>' . (is_numeric($set[1]) ? $set[1] : "'{$set[1]}'") . $logic; break; case 'GT': $where .= " $key " . '>' . (is_numeric($set[1]) ? $set[1] : "'{$set[1]}'") . $logic; break; case 'EGT': $where .= " $key " . '>=' . (is_numeric($set[1]) ? $set[1] : "'{$set[1]}'") . $logic; break; case 'LT': $where .= " $key " . '<' . (is_numeric($set[1]) ? $set[1] : "'{$set[1]}'") . $logic; break; case 'ELT': $where .= " $key " . '<=' . (is_numeric($set[1]) ? $set[1] : "'{$set[1]}'") . $logic; break; case 'EXP': $where .= " $key " . $set[1] . $logic; break; } } } } } } if (!empty($where)) { $where = preg_replace('@(OR|AND|XOR)\s*$@i', '', $where); if (empty($this->opt['where'])) { $this->opt['where'] = " WHERE " . $where; } else if (preg_match('@(OR|AND|XOR)\s*$@i', $this->opt['where'])) { $this->opt['where'] .= $where; } else { $this->opt['where'] .= ' AND ' . $where; } } else { $this->opt['where'] = preg_replace('@(OR|AND|XOR)\s*$@i', '', $this->opt['where']); } } public function field($data, $exclude = false) { if (empty($data)) { return; } if (!is_array($data)) { $data = explode(",", $data); } if ($exclude) { $_data = $data; $fieldData = $this->opt['fieldData']; foreach ($_data as $name => $field) { if (isset($this->opt['fieldData'][$field])) { unset($fieldData[$field]); } } $data = array_keys($fieldData); } $field = ''; foreach ($data as $name => $d) { if (is_string($name)) { $field .= $name . ' AS ' . $d . ","; } else { $field .= $d . ','; } } $this->opt['field'] = substr($field, 0, -1); } public function delAll($table) { return $this->exe("DELETE FROM " . C('DB_PREFIX') . $table); } public function join($join) { $join = preg_replace('@__(\w+)__@', C('DB_PREFIX') . '\1', $join); $this->opt['table'] = $join; } public function limit($data) { $this->opt['limit'] = " LIMIT $data "; } public function order($data) { $this->opt['order'] = " ORDER BY $data "; } public function group($opt) { $this->opt['group'] = " GROUP BY $opt"; } public function having($opt) { $this->opt['having'] = " HAVING $opt"; } public function cache($time = -1) { $this->opt['cacheTime'] = $time; } public function fieldExists($fieldName, $table) { $field = $this->query("DESC " . C("DB_PREFIX") . $table); foreach ($field as $f) { if (strtolower($f['Field']) == strtolower($fieldName)) { return true; } } return false; } public function tableExists($tableName) { $tableArr = $this->query("SHOW TABLES"); foreach ($tableArr as $k => $table) { $tableTrue = $table['Tables_in_' . C('DB_DATABASE')]; if (strtolower($tableTrue) == strtolower(C('DB_PREFIX') . $tableName)) { return true; } } return false; } public function count($field = '*') { $sql = "SELECT count($field) AS c FROM " . $this->opt['table'] .$this->opt['where'] . $this->opt['group'] . $this->opt['having'] .$this->opt['order'] . $this->opt['limit']; $data = $this->query($sql); return $data ? $data[0]['c'] : $data; } public function max($field) { $sql = "SELECT max($field) AS c FROM " .$this->opt['table'] .$this->opt['where'] . $this->opt['group'] . $this->opt['having'] .$this->opt['order'] . $this->opt['limit']; $data = $this->query($sql); return $data ? $data[0]['c'] : $data; } public function min($field) { $sql = "SELECT min($field) AS c FROM " . $this->opt['table'] .$this->opt['where'] . $this->opt['group'] . $this->opt['having'] .$this->opt['order'] . $this->opt['limit']; $data = $this->query($sql); return $data ? $data[0]['c'] : $data; } public function avg($field) { $sql = "SELECT avg($field) AS c FROM " . $this->opt['table'] .$this->opt['where'] . $this->opt['group'] . $this->opt['having'] .$this->opt['order'] . $this->opt['limit']; $data = $this->query($sql); return $data ? $data[0]['c'] : $data; } public function sum($field) { $sql = "SELECT sum($field) AS c FROM " . $this->opt['table'] .$this->opt['where'] . $this->opt['group'] . $this->opt['having'] .$this->opt['order'] . $this->opt['limit']; $data = $this->query($sql); return $data ? $data[0]['c'] : $data; } public function inc($field, $where, $step = 1) { $sql = "UPDATE " . $this->opt['table'] . " SET " . $field . '=' . $field . '+' . $step . " WHERE " . $where; return $this->exe($sql); } public function dec($field, $where, $step = 1) { $sql = "UPDATE " . $this->opt['table'] . " SET " . $field . '=' . $field . '-' . $step . " WHERE " . $where; return $this->exe($sql); } public function createDatabase($database, $charset = "utf8") { return $this->exe("CREATE DATABASE IF NOT EXISTS `$database` CHARSET " . $charset); } public function dropTable($table) { return $this->exe("DROP TABLE IF EXISTS `" . C('DB_PREFIX') . $table . "`"); } public function repair($table) { return $this->exe("REPAIR TABLE `" . C('DB_PREFIX') . $table . "`"); } public function rename($old, $new) { return $this->exe("ALTER TABLE `" . C('DB_PREFIX') . $old . "` RENAME " . C('DB_PREFIX') . $new); } public function optimize($table) { $this->exe("OPTIMIZE TABLE `" . C('DB_PREFIX') . $table . "`"); } public function truncate($table) { return $this->exe("TRUNCATE TABLE `" . C('DB_PREFIX') . $table . "`"); } public function isTable($table) { $table = C('DB_PREFIX') . $table; $info = $this->query('show tables'); foreach ($info as $n => $d) { if ($table == current($d)) { return true; } } return false; } public function getLastSql() { return array_pop(Debug::$sqlExeArr); } public function getAllSql() { return Debug::$sqlExeArr; } protected function recordSql($sql) { if (!preg_match('/\s*show /', $sql)) { Debug::$sqlExeArr[] = $sql; } } protected function error($error) { $this->error = $error; if (DEBUG) { halt($this->error); } else { log_write($this->error); } } public function getAllTableInfo() { $info = $this->query("SHOW TABLE STATUS FROM " . C("DB_DATABASE")); $arr = array(); $arr['total_size'] = 0; $arr['total_row'] = 0; foreach ($info as $k => $t) { $arr['table'][$t['Name']]['tablename'] = $t['Name']; $arr['table'][$t['Name']]['engine'] = $t['Engine']; $arr['table'][$t['Name']]['rows'] = $t['Rows']; $arr['table'][$t['Name']]['collation'] = $t['Collation']; $charset = $arr['table'][$t['Name']]['collation'] = $t['Collation']; $charset = explode("_", $charset); $arr['table'][$t['Name']]['charset'] = $charset[0]; $arr['table'][$t['Name']]['dataFree'] = $t['Data_free']; $arr['table'][$t['Name']]['indexSize'] = $t['Index_length']; $arr['table'][$t['Name']]['dataSize'] = $t['Data_length']; $arr['table'][$t['Name']]['totalSize'] = $t['Data_free'] + $t['Data_length'] + $t['Index_length']; $fieldData = $this->getAllField($t['Name'],true); $arr['table'][$t['Name']]['field'] = $fieldData; $arr['table'][$t['Name']]['primaryKey'] = $this->getPrimaryKey($t['Name'],true); $arr['table'][$t['Name']]['autoincrement'] = $t['Auto_increment'] ? $t['Auto_increment'] : ''; $arr['total_size'] += $arr['table'][$t['Name']]['dataSize']; $arr['total_row'] += $t['Rows']; } return $arr; } public function getDataBaseSize() { $sql = "show table status from " . C("DB_DATABASE"); $data = $this->query($sql); $size = 0; foreach ($data as $v) { $size += $v['Data_length'] + $v['Data_length'] + $v['Index_length'];; } return $size; } public function getTableSize($table) { $table = C('DB_PREFIX') . $table; $sql = "show table status from " . C("DB_DATABASE"); $data = $this->query($sql); foreach ($data as $v) { if ($v['Name'] == $table) { return $v['Data_length'] + $v['Index_length']; } } return 0; } }final class DbFactory { public static $dbFactory = null; protected $driverList = array(); private function __construct() { } public static function factory($driver, $table, $full) { if (is_null(self::$dbFactory)) { self::$dbFactory = new dbFactory(); } if (is_null($driver)) { $driver = ucfirst(C("DB_DRIVER")); } if (isset(self::$dbFactory->driverList[$table]) && self::$dbFactory->driverList[$table]->link) { return self::$dbFactory->driverList[$table]; } if (self::$dbFactory->getDriver($driver, $table, $full)) { return self::$dbFactory->driverList[$table]; } else { return false; } } private function getDriver($driver, $table, $full) { $class = "Db" . $driver; $this->driverList[$table] = new $class; return $this->driverList[$table]->link($table, $full); } private function close() { foreach ($this->driverList as $db) { $db->close(); } } function __destruct() { $this->close(); } }interface DbInterface { public function connect(); public function close(); public function exe($sql); public function query($sql); public function getInsertId(); public function getAffectedRows(); public function getVersion(); public function beginTrans(); public function commit(); public function rollback(); public function escapeString($str); public function link($table, $full); public function table($table, $full = false);}class DbMysql extends Db { static protected $isConnect = false; public $link = null; public function connect() { if (!(self::$isConnect)) { if (C('DB_PCONNECT')) { $link = mysql_pconnect(C("DB_HOST"), C("DB_USER"), C("DB_PASSWORD"), true); } else { $link = mysql_connect(C("DB_HOST"), C("DB_USER"), C("DB_PASSWORD"), true, 131072); } if (!$link) { return false; } else { self::$isConnect = $link; self::setCharts(); } } $this->link = self::$isConnect; mysql_select_db(C("DB_DATABASE"), $this->link); return true; } static private function setCharts() { $character = C("DB_CHARSET"); $sql = "SET character_set_connection=$character,character_set_results=$character,character_set_client=binary"; mysql_query($sql, self::$isConnect); } public function getInsertId() { return mysql_insert_id($this->link); } public function getAffectedRows() { return mysql_affected_rows($this->link); } protected function fetch() { $res = mysql_fetch_assoc($this->lastquery); if (!$res) { $this->resultFree(); } return $res; } public function escapeString($str) { if ($this->link) { return mysql_real_escape_string($str, $this->link); } else { return mysql_escape_string($str); } } public function exe($sql) { $this->optInit(); $this->recordSql($sql); $this->lastquery = mysql_query($sql, $this->link); if ($this->lastquery) { $insert_id = mysql_insert_id($this->link); return $insert_id ? $insert_id : true; } else { $this->error(mysql_error($this->link) . "\t" . $sql); return false; } } public function query($sql) { $cacheTime = is_null($this->opt['cacheTime']) ? C("CACHE_SELECT_TIME") : $this->opt['cacheTime']; $this->optInit(); $cacheName = md5($sql . APP . CONTROLLER . ACTION); if ($cacheTime > -1) { $result = S($cacheName, FALSE, null, array("Driver" => "file", "dir" => APP_CACHE_PATH, "zip" => false)); if ($result) { $this->optInit(); return $result; } } if (!$this->exe($sql)) return false; $list = array(); while (($res = $this->fetch()) != false) { $list [] = $res; } if ($list && $cacheTime >= 0 && count($list) <= C("CACHE_SELECT_LENGTH")) { S($cacheName, $list, $cacheTime, array("Driver" => "file", "dir" => APP_CACHE_PATH, "zip" => false)); } return empty($list) ? array() : $list; } protected function resultFree() { if (isset($this->lastquery)) { mysql_free_result($this->lastquery); } $this->result = null; } public function getVersion() { is_resource($this->link) or $this->connect($this->table); return preg_replace("/[a-z-]/i", "", mysql_get_server_info()); } public function beginTrans() { mysql_query("START AUTOCOMMIT=0"); } public function commit() { mysql_query("COMMIT", $this->link); mysql_query("START AUTOCOMMIT=1"); } public function rollback() { mysql_query("ROLLBACK", $this->link); mysql_query("START AUTOCOMMIT=1"); } public function close() { if (is_resource($this->link)) { mysql_close($this->link); self::$isConnect = null; $this->link = null; } } public function __destruct() { $this->close(); } }class Model { public $table = null; public $db = null; public $trigger = true; public $error; public $data = array(); public $validate = array(); public $auto = array(); public $map = array(); public $alias = array('add' => 'insert', 'save' => 'update', 'all' => 'select', 'del' => 'delete'); public function __construct( $table = null, $full = null, $param = array(), $driver = null ) { if ( ! $this->table) { $this->table = $table; } $this->db = DbFactory::factory($driver, $this->table, $full); if (method_exists($this, "__init")) { $this->__init($param); } } public function __set($var, $value) { $this->data[$var] = $value; } public function __get($name) { if (isset($this->data[$name])) { return $this->data[$name]; } } public function __call($method, $param) { if (isset($this->alias[$method])) { return call_user_func_array( array($this, $this->alias[$method]), $param ); } else if (method_exists($this->db, $method)) { $RETURN = call_user_func_array(array($this->db, $method), $param); return $RETURN === null ? $this : $RETURN; } } protected function __reset() { $this->data = array(); $this->trigger = true; } public function data($data = array()) { if (empty($data)) { if (empty($this->data)) { $this->data = $_POST; } } else { $this->data = $data; } foreach ($this->data as $key => $val) { if (MAGIC_QUOTES_GPC && is_string($val)) { $this->data[$key] = stripslashes($val); } } return $this; } public function create($data = array()) { $this->data($data); $action = array('validate', 'auto', 'map'); foreach ($action as $a) { if ( ! $this->$a()) { return false; } } return true; } public function map($data = array()) { $this->data($data); if ( ! empty($this->map)) { foreach ($this->map as $k => $v) { if (isset($this->data[$k])) { $this->data[$v] = $this->data[$k]; unset($this->data[$k]); } } } return true; } private function getCurrentMethod() { return isset($this->data[$this->db->pri]) ? 2 : 1; } public function validate($data = array()) { if (empty($this->validate)) { return true; } $this->data($data); $data = &$this->data; $motion = $this->getCurrentMethod(); foreach ($this->validate as $v) { $name = $v[0]; $condition = isset($v[3]) ? $v[3] : 2; $action = isset($v[4]) ? $v[4] : 3; if ( ! in_array($action, array($motion, 3))) { continue; } $msg = $v[2]; switch ($condition) { case 1 : if ( ! isset($data[$name])) { continue 2; } break; case 2 : if ( ! isset($data[$name])) { $this->error = $msg; return false; } break; case 3 : if (empty($data[$name])) { continue 2; } break; } if ($pos = strpos($v[1], ':')) { $func = substr($v[1], 0, $pos); $args = substr($v[1], $pos + 1); } else { $func = $v[1]; $args = ''; } if (method_exists($this, $func)) { $res = call_user_func_array( array($this, $func), array($name, $data[$name], $msg, $args) ); if ($res !== true) { $this->error = $res; return false; } } else if (function_exists($func)) { $res = $func($name, $data[$name], $msg, $args); if ($res !== true) { $this->error = $res; return false; } } else { $validate = new Validate(); $func = '_' . $func; if (method_exists($validate, $func)) { $res = call_user_func_array( array($validate, $func), array($name, $data[$name], $msg, $args) ); if ($res !== true) { $this->error = $res; return false; } } } } return true; } public function auto($data = array()) { $this->data($data); $data = &$this->data; $motion = $this->getCurrentMethod(); foreach ($this->auto as $v) { $name = $v[0]; $method = $v[1]; $handle = isset($v[2]) ? $v[2] : "string"; $condition = isset($v[3]) ? $v[3] : 1; $action = isset($v[4]) ? $v[4] : 3; if ( ! in_array($action, array($motion, 3))) { continue; } switch ($condition) { case 1 : if ( ! isset($data[$name])) { continue 2; } break; case 2 : if ( ! isset($data[$name])) { $data[$name] = ''; } break; case 3 : if (empty($data[$name])) { continue 2; } break; case 4: if (empty($data[$name])) { $data[$name] = ''; } else { continue 2; } break; } $data[$name] = isset($data[$name]) ? $data[$name] : ''; switch ($handle) { case "function" : if (function_exists($method)) { $data[$name] = $method($data[$name]); } break; case "method" : if (method_exists($this, $method)) { $data[$name] = $this->$method($data[$name]); } break; case "string" : $data[$name] = $method; break; } } return true; } public function trigger($status) { $this->trigger = $status; return $this; } public function delete($where = '') { $this->trigger && method_exists($this, '__before_delete') && $this->__before_delete(); $return = $this->db->delete($where); $this->trigger && method_exists($this, '__after_delete') && $this->__after_delete($return); $this->__reset(); return $return; } public function find($where = '') { $result = $this->select($where); return is_array($result) ? current($result) : $result; } public function select($where = '') { $this->trigger && method_exists($this, '__before_select') && $this->__before_select(); $return = $this->db->select($where); $this->trigger && method_exists($this, '__after_select') && $this->__after_select($return); $this->__reset(); return $return; } public function update($data = array()) { $this->data($data); $this->trigger && method_exists($this, '__before_update') && $this->__before_update($this->data); $return = $this->db->update($this->data); $this->trigger && method_exists($this, '__after_update') && $this->__after_update($return); $this->__reset(); return $return; } public function insert($data = array()) { $this->data($data); $this->trigger && method_exists($this, '__before_insert') && $this->__before_insert($this->data); $return = $this->db->insert($this->data); $this->trigger && method_exists($this, '__after_insert') && $this->__after_insert($return); $this->__reset(); return $return; } public function replace($data = array()) { $this->data($data); $this->trigger && method_exists($this, '__before_insert') && $this->__before_insert($this->data); $return = $this->db->replace($this->data); $this->trigger && method_exists($this, '__after_insert') && $this->__after_insert($return); $this->__reset(); return $return; } }defined("HAS_ONE") or define("HAS_ONE", "HAS_ONE"); defined("HAS_MANY") or define("HAS_MANY", "HAS_MANY"); defined("BELONGS_TO") or define("BELONGS_TO", "BELONGS_TO"); defined("MANY_TO_MANY") or define("MANY_TO_MANY", "MANY_TO_MANY"); class RelationModel extends Model { public $relation = array(); public function select($data = array()) { $result = call_user_func(array($this->db, __FUNCTION__), $data); $this->__reset(); if (!$result) { return $result; } foreach ($this->relation as $table => $set) { $pk = $set['parent_key']; $fk = $set['foreign_key']; $db = M($table); $field = isset($set['field']) ? $set['field'] : ''; switch ($set['type']) { case HAS_ONE: foreach ($result as $n => $d) { $s = $db->field($field)->where($fk . '=' . $d[$pk])->find(); if (is_array($s)) { $result[$n] = array_merge($d, $s); } } break; case HAS_MANY: foreach ($result as $n => $d) { $s = $db->field($field)->where($fk . '=' . $d[$pk])->all(); if (is_array($s)) { $result[$n][$table] = $s; } } break; case BELONGS_TO: foreach ($result as $n => $d) { $s = $db->field($field)->where($fk . '=' . $d[$pk])->find(); if (is_array($s)) { $result[$n] = array_merge($d, $s); } } break; case MANY_TO_MANY: foreach ($result as $n => $d) { $s = $db->table($set['relation_table'])->field($fk)->where($pk . '=' . $d[$pk])->getField($fk, true); if (is_array($s)) { $map[$fk] = array('IN', $s); $result[$n][$table] = $db->table($table)->where($map)->all(); } } break; } } return $result; } public function insert($data = array()) { $this->data($data); $InsertData = $this->data; $pid = call_user_func(array($this->db, __FUNCTION__), $InsertData); $this->__reset(); if (!$pid) { return $pid; } $result = array(); $result[$this->table] = $pid; foreach ($this->relation as $table => $set) { if (empty($InsertData[$table])) { continue; } $pk = $set['parent_key']; $fk = $set['foreign_key']; $db = M($table); switch ($set['type']) { case HAS_ONE: case HAS_MANY: $InsertData[$table][$fk] = $pid; $result[$table] = $db->insert($InsertData[$table]); break; case BELONGS_TO: $fid = $db->add($InsertData[$table]); $db->table($this->table)->where($pk . "=" . $pid)->save(array($pk => $fid)); $result[$table] = $fid; break; case MANY_TO_MANY: $fid = $db->add($InsertData[$table]); $result[$table] = $fid; $db->table($set['relation_table'])->insert(array($pk => $pid, $fk => $fid)); } } return $result; } public function update($data = array()) { $this->data($data); $UpdateData = $this->data; $status = call_user_func(array($this->db, __FUNCTION__), $UpdateData); $this->__reset(); if (!$status) { return $status; } $pid = $UpdateData[$this->db->pri]; foreach ($this->relation as $table => $set) { if (empty($UpdateData[$table])) { continue; } $fk = $set['foreign_key']; $db = M($table); switch ($set['type']) { case HAS_ONE: $db->where("$fk=$pid")->save($UpdateData[$table]); break; case HAS_MANY: case BELONGS_TO: case MANY_TO_MANY: $db->save($UpdateData[$table]); break; } } return $status; } public function delete($data = array()) { $this->where($data); $where = preg_replace('/^\s+where/i', '', $this->db->opt['where']); $ParentData = $this->where($where)->select(); $status = call_user_func(array($this->db, __FUNCTION__), $where); $this->__reset(); if (!$this->db->getAffectedRows()) { return true; } if (!$status) { return $status; } foreach ($this->relation as $table => $set) { $pk = $set['parent_key']; $fk = $set['foreign_key']; $db = M($table); switch ($set['type']) { case HAS_ONE: case HAS_MANY: foreach ($ParentData as $p) { $db->where($fk . '=' . $p[$pk])->delete(); } break; case BELONGS_TO: break; case MANY_TO_MANY: foreach ($ParentData as $p) { $db->table($set['relation_table'])->where($pk . '=' . $p[$pk])->delete(); } break; } } return $status; } }class ViewModel extends Model { public $view = array(); private $queryMethod = array( 'select', 'find', 'count', 'max', 'min', 'avg', 'sum' ); public function __call($method, $param) { if (in_array($method, $this->queryMethod)) { $this->setDriverOption(); } return parent::__call($method, $param); } private function setDriverOption() { if (empty($this->view)) { return; } else { $this->setTable(); $this->setField(); } } public function find($where = '') { $result = $this->select($where); return is_array($result) ? current($result) : $result; } public function select($where = '') { $this->setDriverOption(); $this->trigger && method_exists($this, '__before_select') && $this->__before_select(); $return = $this->db->select($where); $this->trigger && method_exists($this, '__after_select') && $this->__after_select($return); $this->__reset(); return $return; } private function setTable() { $from = ''; foreach ($this->view as $table => $set) { $as = isset($set['_as']) ? $set['_as'] : $table; $from .= C('DB_PREFIX') . $table . ' ' . $as; if (isset($set['_on'])) { $from .= " ON  " . $set['_on']; } if (isset($set['_type'])) { $from .= ' ' . strtoupper($set['_type']) . ' JOIN '; } } $this->db->opt['table'] = preg_replace('@(INNER|RIGHT|LEFT)\s*JOIN\s*$@', '', $from); } private function setField() { if ($this->db->opt['field'] != '*') { return $this->db->opt['field']; } else { $field = ''; foreach ($this->view as $table => $set) { if (!isset($set['_field'])) { continue; } else { $field .= $set['_field'] . ','; } } if (!empty($field)) { $this->db->opt['field'] = substr($field, 0, -1); } } } }final class ViewHd { public $vars = array(); public $const = array(); public $tplFile = null; public $compileFile = null; public function display( $tplFile = null, $cacheTime = -1, $cachePath = null, $contentType = "text/html", $show = true ) { $cacheName = md5($_SERVER['REQUEST_URI']); $cacheTime = is_numeric($cacheTime) ? $cacheTime : intval( C("TPL_CACHE_TIME") ); $cachePath = $cachePath ? $cachePath : APP_CACHE_PATH; $content = null; if ($cacheTime >= 0) { $content = S( $cacheName, false, $cacheTime, array("dir" => $cachePath, 'zip' => false, "Driver" => "File") ); } if (!$content) { $this->vars['hd']['get'] = &$_GET; $this->vars['hd']['post'] = &$_POST; $this->vars['hd']['request'] = &$_REQUEST; $this->vars['hd']['cookie'] = &$_COOKIE; $this->vars['hd']['session'] = &$_SESSION; $this->vars['hd']['server'] = &$_SERVER; $this->vars['hd']['config'] = C(); $this->vars['hd']['language'] = L(); $this->vars['hd']['const'] = get_defined_constants(); $this->tplFile = $this->getTemplateFile($tplFile); if (!$this->tplFile) { return; } $this->compileFile = APP_COMPILE_PATH . MODULE . '/' . CONTROLLER . '/' . ACTION . '_' . substr(md5($this->tplFile), 0, 8) . '.php'; if (DEBUG) { Debug::$tpl[] = array(basename($this->tplFile), $this->compileFile); } if ($this->compileInvalid($tplFile)) { $this->compile(); } if (!empty($this->vars)) { extract($this->vars); } ob_start(); include($this->compileFile); $content = ob_get_clean(); if ($cacheTime >= 0) { S( $cacheName, $content, $cacheTime, array("dir" => $cachePath, 'zip' => false, "Driver" => "File") ); } } if ($show) { $charset = C('TPL_CHARSET') ? C('TPL_CHARSET') : "UTF-8"; if (!headers_sent()) { header("Content-type:" . $contentType . ';charset=' . $charset); } echo $content; } else { return $content; } } public function fetch( $tplFile = null, $cacheTime = null, $cachePath = null, $contentType = "text/html" ) { return $this->display( $tplFile, $cacheTime, $cachePath, $contentType, false ); } public function isCache($cachePath = null) { $cachePath = $cachePath ? $cachePath : APP_CACHE_PATH; $cacheName = md5($_SERVER['REQUEST_URI']); return S( $cacheName, false, null, array("dir" => $cachePath, "Driver" => "File") ) ? true : false; } private function getTemplateFile($file) { if (is_null($file)) { $file = CONTROLLER_VIEW_PATH . ACTION; } if (!is_file($file)) { if (!strstr($file, '/')) { $file = CONTROLLER_VIEW_PATH . $file; } if (!preg_match('/\.[a-z]$/i', $file)) { $file .= C('TPL_FIX'); } } if (is_file($file)) { return $file; } else { DEBUG && halt("模板不存在:$file"); return false; } } private function compileInvalid() { $tplFile = $this->tplFile; $compileFile = $this->compileFile; return DEBUG || !file_exists($compileFile) || (filemtime($tplFile) > filemtime($compileFile)); } public function compile() { if (!$this->compileInvalid()) { return; } $compileObj = new ViewCompile(); $compileObj->run($this); } public function assign($var, $value) { if (is_array($var)) { foreach ($var as $k => $v) { if (is_string($k)) { $this->vars[$k] = $v; } } } else { $this->vars[$var] = $value; } } }final class ViewFactory { public static $viewFactory = null; protected $driverList = array(); private function __construct() { } public static function factory($driver = null) { if (is_null(self::$viewFactory)) { self::$viewFactory = new viewFactory(); } if (is_null($driver)) { $driver = ucfirst(strtolower(C("TPL_ENGINE"))); } if (isset(self::$viewFactory->driverList[$driver])) { return self::$viewFactory->driverList[$driver]; } self::$viewFactory->getDriver($driver); return self::$viewFactory->driverList[$driver]; } public function getDriver($driver) { $class = "View" . ucfirst($driver); if (!class_exists($class, false)) { $classFile = HDPHP_DRIVER_PATH . 'View/' . $class . '.class.php'; if (!require_cache($classFile)) { DEBUG && halt($classFile . "不存在"); } } $this->driverList[$driver] = new $class(); return true; } }import('HDPHP.Lib.Driver.View.Tag'); class ViewCompile { private $view; private $content; private $aliasFunction = array( 'default' => '_default' ); private $literal = array(); function __construct() { } public function run(&$view = null) { $this->view = $view; $this->content = file_get_contents($this->view->tplFile); $this->getNoParseContent(); $this->parseTag(); $this->parseVar(); $this->parseUrlConst(); $this->replaceNoParseContent(); $this->content = "<?php if(!defined('HDPHP_PATH'))exit;C('SHOW_NOTICE',FALSE);?>\n" . $this->content; Dir::create(dirname($this->view->compileFile)); Dir::safeFile(dirname($this->view->compileFile)); file_put_contents($this->view->compileFile, $this->content); } private function getNoParseContent() { $status = preg_match_all( '@<literal>(.*?)<\/literal>@isU', $this->content, $info, PREG_SET_ORDER ); if ($status) { foreach ($info as $n => $content) { if ( ! empty($content)) { $this->literal[$n] = $content[1]; $this->content = str_replace( $content[0], '###' . $n . '###', $this->content ); } } } } private function replaceNoParseContent() { foreach ($this->literal as $n => $content) { $this->content = str_replace( '###' . $n . '###', $content, $this->content ); } } private function parseTag() { $tagClass = array(); if (import('HDPHP.Lib.Driver.View.ViewTag')) { $tagClass[] = 'ViewTag'; } $tags = C('TPL_TAGS'); if ( ! empty($tags) && is_array($tags)) { foreach ($tags as $file) { if (import($file) || import($file, MODULE_TAG_PATH) || import($file, APP_TAG_PATH) ) { $file=str_replace('.','/',$file); $class = basename($file); if (class_exists($class, false) && property_exists($class, 'Tag') && get_parent_class($class) == 'Tag' ) { $tagClass[] = $class; } } } } foreach ($tagClass as $class) { $obj = new $class(); foreach ($obj->Tag as $tag => $option) { if ( ! isset($option['block']) || ! isset($option['level']) ) { continue; } for ($i = 0; $i <= $option['level']; $i++) { if ( ! $obj->parseTag($tag, $this->content, $this->view) ) { break; } } } } } private function parseVar() { $preg = '#\{(\$[\w\.\[\]\'"]+)?(?:\|(.*))?\}#isU'; $status = preg_match_all( $preg, $this->content, $info, PREG_SET_ORDER ); if ($status) { foreach ($info as $d) { $var = ''; if ( ! empty($d[1])) { $data = explode('.', $d[1]); foreach ($data as $n => $m) { if ($n == 0) { $var .= $m; } else { $var .= '[\'' . $m . '\']'; } } } if ( ! empty($d[2])) { $functions = explode('|', $d[2]); foreach ($functions as $func) { $tmp = explode(':', $func, 2); if (isset($this->aliasFunction[$tmp[0]])) { $name = $this->aliasFunction[$tmp[0]]; } else { $name = $tmp[0]; } $arg = empty($tmp[1]) ? '' : $tmp[1]; if (strstr($arg, '@@')) { $var = str_replace('@@', $var, $arg); } else { $var = $var . ',' . $arg; } $var = trim($var, ','); $var = $name . '(' . $var . ')'; } } if(!empty($var)){ $replace = '<?php echo ' . $var . ';?>'; $this->content = str_replace($d[0], $replace, $this->content); } } } } private function parseUrlConst() { $const = get_defined_constants(true); foreach ($const['user'] as $k => $v) { if (strstr($k, '__')) { $this->content = str_replace($k, $v, $this->content); } } } }final class Dir { static public function dirPath($dir_name) { $dirname = str_ireplace("\\", "/", $dir_name); return substr($dirname, "-1") == "/" ? $dirname : $dirname . "/"; } static public function getExt($file) { return strtolower(substr(strrchr($file, "."), 1)); } static public function tree($dirName = null, $exts = '', $son = 0, $list = array()) { if (is_null($dirName)) $dirName = '.'; $dirPath = self::dirPath($dirName); static $id = 0; if (is_array($exts)) $exts = implode("|", $exts); foreach (glob($dirPath . '*') as $v) { $id++; if (is_dir($v) || !$exts || preg_match("/\.($exts)/i", $v)) { $list [$id] ['type'] = filetype($v); $list [$id] ['filename'] = basename($v); $path = str_replace("\\", "/", realpath($v)) . (is_dir($v) ? '/' : ''); $list [$id] ['path']=$path; $list [$id] ['spath']=ltrim(str_replace(dirname($_SERVER['SCRIPT_FILENAME']),'',$path),'/'); $list [$id] ['filemtime'] = filemtime($v); $list [$id] ['fileatime'] = fileatime($v); $list [$id] ['size'] = is_file($v) ? filesize($v) : self::get_dir_size($v); $list [$id] ['iswrite'] = is_writeable($v) ? 1 : 0; $list [$id] ['isread'] = is_readable($v) ? 1 : 0; } if ($son) { if (is_dir($v)) { $list = self::tree($v, $exts, $son = 1, $list); } } } return $list; } static public function get_dir_size($f) { $s = 0; foreach (glob($f . '/*') as $v) { $s += is_file($v) ? filesize($v) : self::get_dir_size($v); } return $s; } static public function treeDir($dirName = null, $son = 0, $pid = 0, $dirs = array()) { if (!$dirName) $dirName = '.'; static $id = 0; $dirPath = self::dirPath($dirName); foreach (glob($dirPath . "*") as $v) { if (is_dir($v)) { $id++; $dirs [$id] = array("id" => $id, 'pid' => $pid, "dirname" => basename($v), "dirpath" => $v); if ($son) { $dirs = self::treeDir($v, $son, $id, $dirs); } } } return $dirs; } static public function del($dirName) { if (is_file($dirName)) { unlink($dirName); return true; } $dirPath = self::dirPath($dirName); if (!is_dir($dirPath)) return true; foreach (glob($dirPath . "*") as $v) { is_dir($v) ? self::del($v) : unlink($v); } return @rmdir($dirName); } static public function create($dirName, $auth = 0755) { $dirPath = self::dirPath($dirName); if (is_dir($dirPath)) return true; $dirs = explode('/', $dirPath); $dir = ''; foreach ($dirs as $v) { $dir .= $v . '/'; if (is_dir($dir)) continue; mkdir($dir, $auth); } return is_dir($dirPath); } static public function copy($olddir, $newdir, $strip_space = false) { $olddir = self::dirPath($olddir); $newdir = self::dirPath($newdir); if (!is_dir($olddir)) error("复制失败：" . $olddir . "目录不存在"); if (!is_dir($newdir)) self::create($newdir); foreach (glob($olddir . '*') as $v) { $to = $newdir . basename($v); if (is_file($to)) continue; if (is_dir($v)) { self::copy($v, $to, $strip_space); } else { if ($strip_space) { $data = file_get_contents($v); file_put_contents($to, strip_space($data)); } else { copy($v, $to); } chmod($to, "0777"); } } return true; } static public function safeFile($dirName, $recursive = false) { $file = HDPHP_TPL_PATH . '/index.html'; if (!is_dir($dirName)) { return; } $dirPath = self::dirPath($dirName); if (!is_file($dirPath . 'index.html')) { copy($file, $dirPath . 'index.html'); } if ($recursive) { foreach (glob($dirPath . "*") as $d) { is_dir($d) and self::safeFile($d); } } } }C(array ( 'DEFAULT_TIME_ZONE' => 'PRC', 'LANGUAGE' => '', 'CHECK_FILE_CASE' => true, 'AUTO_LOAD_FILE' => array ( ), 'FILTER_FUNCTION' => array ( 0 => 'htmlspecialchars', 1 => 'strip_tags', ), 'DB_DRIVER' => 'Mysqli', 'DB_CHARSET' => 'utf8', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => 3306, 'DB_USER' => 'root', 'DB_PASSWORD' => '', 'DB_DATABASE' => '', 'DB_PREFIX' => '', 'DB_PCONNECT' => false, 'CACHE_SELECT_TIME' => -1, 'CACHE_SELECT_LENGTH' => 30, 'TPL_CHARSET' => 'utf-8', 'TPL_PATH' => 'View', 'TPL_STYLE' => '', 'TPL_FIX' => '.html', 'TPL_TAGS' => array ( ), 'TPL_ERROR' => 'error', 'TPL_SUCCESS' => 'success', 'TPL_ENGINE' => 'HD', 'TPL_TAG_LEFT' => '<', 'TPL_TAG_RIGHT' => '>', 'TPL_CACHE_TIME' => -1, 'STORAGE_DRIVER' => 'File', '404_URL' => '', 'ERROR_URL' => '', 'ERROR_MESSAGE' => '网站出错了，请稍候再试...', 'SHOW_NOTICE' => true, 'LOG_SIZE' => 2000000, 'LOG_RECORD' => true, 'LOG_LEVEL' => array ( 0 => 'FATAL', 1 => 'ERROR', 2 => 'WARNING', 3 => 'SQL', ), 'LOG_EXCEPTION_RECORD' => true, 'SESSION_AUTO_START' => true, 'SESSION_TYPE' => '', 'SESSION_OPTIONS' => array ( ), 'COOKIE_EXPIRE' => 0, 'COOKIE_DOMAIN' => '', 'COOKIE_PATH' => '/', 'COOKIE_PREFIX' => '', 'HTTPS' => false, 'URL_REWRITE' => false, 'URL_TYPE' => 1, 'PATHINFO_DLI' => '/', 'PATHINFO_VAR' => 'q', 'HTML_SUFFIX' => '', 'VAR_GROUP' => 'g', 'VAR_MODULE' => 'm', 'VAR_CONTROLLER' => 'c', 'VAR_ACTION' => 'a', 'DENY_MODULE' => array ( 0 => 'Common', 1 => 'Temp', 2 => 'Addons', ), 'DEFAULT_MODULE' => 'Index', 'DEFAULT_CONTROLLER' => 'Index', 'DEFAULT_ACTION' => 'index', 'CONTROLLER_FIX' => 'Controller', 'MODEL_FIX' => 'Model', 'UPLOAD_THUMB_ON' => false, 'UPLOAD_ALLOW_TYPE' => array ( 0 => 'jpg', 1 => 'jpeg', 2 => 'gif', 3 => 'png', 4 => 'zip', 5 => 'rar', 6 => 'doc', 7 => 'txt', ), 'UPLOAD_ALLOW_SIZE' => 2097152, 'UPLOAD_PATH' => 'Upload/', 'WATER_ON' => true, 'WATER_FONT' => 'D:/wamp/www/ZBZphp/wowsai/hdphp/Data/Font/font.ttf', 'WATER_IMG' => 'D:/wamp/www/ZBZphp/wowsai/hdphp/Data/Image/water.png', 'WATER_POS' => 9, 'WATER_PCT' => 60, 'WATER_QUALITY' => 80, 'WATER_TEXT' => 'WWW.HOUDUNWANG.COM', 'WATER_TEXT_COLOR' => '#f00f00', 'WATER_TEXT_SIZE' => 12, 'THUMB_PREFIX' => '', 'THUMB_ENDFIX' => '_thumb', 'THUMB_TYPE' => 6, 'THUMB_WIDTH' => 300, 'THUMB_HEIGHT' => 300, 'CODE_FONT' => 'D:/wamp/www/ZBZphp/wowsai/hdphp/Data/Font/font.ttf', 'CODE_STR' => '23456789abcdefghjkmnpqrstuvwsyz', 'CODE_WIDTH' => 120, 'CODE_HEIGHT' => 35, 'CODE_BG_COLOR' => '#ffffff', 'CODE_LEN' => 4, 'CODE_FONT_SIZE' => 20, 'CODE_FONT_COLOR' => '', 'PAGE_VAR' => 'page', 'PAGE_ROW' => 10, 'PAGE_SHOW_ROW' => 10, 'PAGE_STYLE' => 2, 'PAGE_DESC' => array ( 'pre' => '上一页', 'next' => '下一页', 'first' => '首页', 'end' => '尾页', 'unit' => '条', ), 'RBAC_TYPE' => 1, 'RBAC_SUPER_ADMIN' => 'super_admin', 'RBAC_USERNAME_FIELD' => 'username', 'RBAC_PASSWORD_FIELD' => 'password', 'RBAC_AUTH_KEY' => 'uid', 'RBAC_NO_AUTH' => array ( ), 'RBAC_USER_TABLE' => 'user', 'RBAC_ROLE_TABLE' => 'role', 'RBAC_NODE_TABLE' => 'node', 'RBAC_ROLE_USER_TABLE' => 'user_role', 'ACCESS_TABLE' => 'access', 'CACHE_TYPE' => 'file', 'CACHE_TIME' => 0, 'CACHE_MEMCACHE' => array ( 'host' => '127.0.0.1', 'port' => 11211, 'timeout' => 1, 'weight' => 1, 'pconnect' => 1, ), 'CACHE_REDIS' => array ( 'host' => '127.0.0.1', 'port' => 6379, 'password' => '', 'timeout' => 1, 'Db' => 0, 'pconnect' => 0, ), 'ROUTE' => array ( ), 'HOOK' => array ( ), 'ALIAS' => array ( ), ));L(array ( ));alias_import(array ( ));HDPHP::init();App::run();?>